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.


The one often-quoted is:

zip(*[iter(l)] * 2)

I prefer this more readable version of the iter solution:

it = iter(l)
list(zip(it, it))
# [(1, 2), (3, 4), (5, 6)]

How about using the step feature of range():

[(l[n],l[n+1]) for n in range(0,len(l),2)]