Iterate through list two items at a time

Jeffrey Froman jeffrey at fro.man
Tue Jan 2 22:59:26 EST 2007


Dave Dean wrote:

>  I'm looking for a way to iterate through a list, two (or more) items at a
> time.

Here's a solution, from the iterools documentation. It may not be the /most/
beautiful, but it is short, and scales well for larger groupings:

>>> from itertools import izip
>>> def groupn(iterable, n):
...     return izip(* [iter(iterable)] * n)
... 
>>> list(groupn(myList, 2))
[(0, 1), (2, 3), (4, 5), (6, 7), (8, 9), (10, 11)]
>>> list(groupn(myList, 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)]
>>> list(groupn(myList, 4))
[(0, 1, 2, 3), (4, 5, 6, 7), (8, 9, 10, 11)]
>>> for a,b in groupn(myList, 2):
...     print a, b
... 
0 1
2 3
4 5
6 7
8 9
10 11
>>> 

Jeffrey





More information about the Python-list mailing list