tags:

views:

62

answers:

1

Hey I just wanna know what is pythons equivalent of Ruby's each_slice(count)

Like I wanna take 2 elements from list for each iteration.

Like for [1,2,3,4,5,6] i wanna handle 1,2 in first iteration then 3,4 then 5,6.

Ofcourse there is a roundabout way using index values. But is there a direct function or someway to do this directly?

Thank you

+4  A: 

There is a recipe for this in the itertools documentation called grouper:

from itertools import izip_longest
def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

Use like this:

>>> l = [1,2,3,4,5,6]
>>> for a,b in grouper(2, l):
>>>     print a, b

1 2
3 4
5 6
Mark Byers