Alternative way to split a list into groups of n

python

Solution

A Python recipe (In Python 2.6, use `itertools.izip_longest`):

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return itertools.zip_longest(*args, fillvalue=fillvalue)

Example usage:

>>> list(grouper(3, range(9)))
[(0, 1, 2), (3, 4, 5), (6, 7, 8)]
>>> list(grouper(3, range(10)))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]

If you want the last group to be shorter than the others instead of padded with `fillvalue`, then you could e.g. change the code like this:

>>> def mygrouper(n, iterable):
...     args = [iter(iterable)] * n
...     return ([e for e in t if e != None] for t in itertools.zip_longest(*args))
... 
>>> list(mygrouper(3, range(9)))
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]
>>> list(mygrouper(3, range(10)))
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

Problem

Let's say I have a list of arbitrary length, L: ``` L = list(range(1000)) ``` What is the best way to split that list into groups of `n`? This is the best structure that I have been able to come up with, and for some reason it does not feel like it is the best way of accomplishing the task: ``` n = 25 for i in range(0, len(L), n): chunk = L[i:i+25] ``` Is there a built-in to do this I'm missing? Edit: Early answers are reworking my for loop into a listcomp, which is not the idea; you're basically giving me my exact answer back in a different form. I'm seeing if there's an alternate means to accomplish this, like a hypothetical `.split` on lists or something. I also do use this as a generator in some code that I wrote last night: ``` def split_list(L, n): assert type(L) is list, "L is not a list" for i in range(0, len(L), n): yield L[i:i+n] ```

Original source

Related problems