Iterating a sequence two items at a time

Ulrich Eckhardt eckhardt at satorlaser.com
Tue May 11 03:09:42 EDT 2010


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.


def as_pairs(seq):
    i = iter(seq)
    yield (i.next(), i.next())

Question to this code: Is the order of the "i.next()" calls guaranteed to be
from left to right? Or could I end up with pairs being switched?

Thanks!

Uli

-- 
Sator Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932




More information about the Python-list mailing list