1

Possible Duplicate:
How do you split a list into evenly sized chunks in Python?

The idea is quite simple, I want to do something like this:

for elem1, elem2, elem3 in list:
    <some code>

For this to work we need that list would be a list of 3-iterables, something like this:

list = [[1, 2, 3], [4, 5, 6]]

But, what can I do if this list is just a regular list?

list = [1, 2, 3, 4, 5, 6]

Is there any fast and simple way of transform this regular list into the list of 3-iterables so the loop would work? Or n-iterables, I use 3 here just as an example.

Thanks.

Community
  • 1
  • 1
Ole
  • 366
  • 1
  • 3
  • 13
  • 1
    Like this: http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python ? – georg Jan 14 '13 at 08:06
  • Ok thanks, sorry if I have asked the same, I tried to search before asking but I didn't found anything – Ole Jan 14 '13 at 09:24

1 Answers1

5

Use the grouper recipe from itertools:

def grouper(n, iterable, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

And something like:

for a, b, c in grouper(3, some_list):
    pass # whatever
Jon Clements
  • 138,671
  • 33
  • 247
  • 280