Python “Every Other Element” Idiom [duplicate]

This will do it a bit more neatly:

>>> data = [1,2,3,4,5,6]
>>> zip(data[0::2], data[1::2])
[(1, 2), (3, 4), (5, 6)]

(but it’s arguably less readable if you’re not familiar with the “stride” feature of ranges).

Like your code, it discards the last value where you have an odd number of values.

Leave a Comment