Splitting a list into even chunks.
- chunk
- split
- list
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):
yield from iter(lambda it=iter(iterable): list(islice(it, n)), [])
# Or in Python 2.7, where `yield from` doesn't exist yet, use:
# for chunk in iter(lambda it=iter(iterable): list(islice(it, n)), []):
# yield chunk