Iterating a sequence two items at a time

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Tue May 11 04:05:37 EDT 2010


Ulrich Eckhardt a écrit :
> Hi!
> 
> I have a list [1,2,3,4,5,6] which I'd like to iterate as (1,2), (3,4),
> (5,6). I can of course roll my own, but I was wondering if there was
> already some existing library function that already does this.



 >>> l = range(10)
 >>> for x, y in zip(l[::2], l[1::2]):
...   print x, y
...
0 1
2 3
4 5
6 7
8 9

SimplestThingThatCouldPossiblyWork(tm) - but might not be the most 
efficient idiom, specially with large lists...





More information about the Python-list mailing list