Splitting a list into even chunks.
- list
- split
Using the grouper
recipe from the itertools
documentation:
>>> from itertools import zip_longest # Use izip_longest for Python 2.x
>>> def grouper(iterable, n, fillvalue=None):
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
>>> list(grouper(a, 3))
[(1, 2, 3), (4, 5, 6), (7, None, None)]
Another approach to exclude worrying about fill values (although it’s slightly less efficient) is to build a list of the certain chunk size and yield, eg:
from itertools import islice
def grouper(iterable, n):
for chunk in iter(lambda i=iter(iterable): list(islice(i, n)), []):
yield chunk
# Or in Py 3.x, just use:
# yield from iter(lambda i=iter(iterable): list(islice(i, n)), [])