Iterate through list two items at a time

J. Clifford Dyer webmaster at cacradicalgrace.org
Wed Jan 3 17:15:58 EST 2007


Gabriel Genellina wrote:
> b=iter(a)
> for x in b:
>    y=b.next()
>    print x,y
> 

So as not to choke on odd-length lists, you could try

a = [1,2,3,4,5,6,7]
b = iter(a)
for x in b:
    try:
         y=b.next()
    except StopIteration:
         y=None
    print x,y

Substitute in whatever for y=None that you like.

Cheers,
Cliff



More information about the Python-list mailing list