pairs from a list

Arnaud Delobelle arnodel at googlemail.com
Tue Jan 22 02:11:23 EST 2008


On Jan 22, 3:20 am, Alan Isaac <ais... at american.edu> wrote:
> I want to generate sequential pairs from a list.
> Here is a way::
>
>     from itertools import izip, islice
>     for x12 in izip(islice(x,0,None,2),islice(x,1,None,2)):
>         print x12
>
> (Of course the print statement is just illustrative.)
> What is the fastest way? (Ignore the import time.)
>
> Thanks,
> Alan Isaac

Don't know the fastest, but here's a very concise way:

from itertools import izip

def ipairs(seq):
    it = iter(seq)
    return izip(it, it)

>>> list(pairs(xrange(10)))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9)]
>>> list(pairs('hello'))
[('h', 'e'), ('l', 'l')]

--
Arnaud




More information about the Python-list mailing list