Iterate through list two items at a time

bearophileHUGS at lycos.com bearophileHUGS at lycos.com
Tue Jan 2 21:37:30 EST 2007


Few alternative solutions (other are possible), I usually use a variant
of the first version, inside a partition function, the second variant
is shorter when you don't have a handy partition() function and you
don't want to import modules, and the forth one needs less memory when
the data is very long:

from itertools import izip, islice

data = [1,2,3,4,5,6,7]

for x1, x2 in (data[i:i+2] for i in xrange(0, len(data)/2*2, 2)):
    print x1, x2

for x1, x2 in zip(data[::2], data[1::2]):
    print x1, x2

for x1, x2 in izip(data[::2], data[1::2]):
    print x1, x2

for x1, x2 in izip(islice(data,0,None,2), islice(data,1,None,2)):
    print x1, x2

Bye,
bearophile




More information about the Python-list mailing list