a sequence question

Duncan Booth duncan.booth at invalid.invalid
Fri Jan 28 10:30:43 EST 2005

Chris Wright wrote:

> 1) I want to iterate over a list "N at a time"
> sort of like:
> # Two at a time... won't work, obviously
> >>> for a, b in [1,2,3,4]:
> ...      print a,b
> ...      

Try this:

l = [1, 2, 3, 4]
for a, b in zip(*[iter(l)]*2):
   print a, b

zip(*[iter(seq)]*N) will group by N (but if there are any odd items at the 
end it will ignore them).

map(None, *[iter(seq)]*N) will group by N padding the last item with None 
if it needs to.

More information about the Python-list mailing list