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


-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to