Iterate through list two items at a time

Peter Otten __peter__ at web.de
Thu Jan 4 07:46:25 EST 2007


Wade Leftwich wrote:

> from itertools import groupby
> 
> def chunk(it, n=0):
>     if n == 0:
>         return iter([it])
>     def groupfun((x,y)):
>         return int(x/n)
>     grouped = groupby(enumerate(it), groupfun)
>     counted = (y for (x,y) in grouped)
>     return ((z for (y,z) in x) for x in counted)
> 
>>>> [list(x) for x in chunk(range(10), 3)]
> [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
> 
>>>> [x for x in chunk(range(10), 3)]
> [<generator object at 0xb7a34e4c>,
>  <generator object at 0xb7a34dac>,
>  <generator object at 0xb7a34d2c>,
>  <generator object at 0xb7a34d6c>]

Note that all but the last of these generators are useless:

>>> chunks = [x for x in chunk(range(10), 3)]
>>> [list(x) for x in chunks]
[[], [], [], [9]] # did you expect that?

Peter



More information about the Python-list mailing list