idiomatic way to take groups of n items from a list in Python?

Posted by Wang on Stack Overflow See other posts from Stack Overflow or by Wang
Published on 2010-03-17T10:35:13Z Indexed on 2010/03/17 11:31 UTC
Read the original article Hit count: 226

Filed under:
|

Given a list

A = [1 2 3 4 5 6]

Is there any idiomatic (Pythonic) way to iterate over it as though it were

B = [(1, 2) (3, 4) (5, 6)]

other than indexing? That feels like a holdover from C:

for a1,a2 in [ (A[i], A[i+1]) for i in range(0, len(A), 2) ]:

I can't help but feel there should be some clever hack using itertools or slicing or something.

(Of course, two at a time is just an example; I'd like a solution that works for any n.)

Edit: related http://stackoverflow.com/questions/1162592/iterate-over-a-string-2-or-n-characters-at-a-time-in-python but even the cleanest solution (accepted, using zip) doesn't generalize well to higher n without a list comprehension and *-notation.

© Stack Overflow or respective owner

Related posts about python

Related posts about iteration