I'm running Python 3.7.3. I have an iterable which I want to group into iterables of up to N items. This is almost the grouper() recipe from itertools, except that I don't want the last group padded. The best I've been able to come up with is:
from itertools import zip_longest
# From https://docs.python.org/3.7/library/itertools.html#itertools-recipes
def grouper(iterable, n):
args = [iter(iterable)] * n
for group in zip_longest(*args):
yield (item for item in group if item)
names = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
for group in grouper(names, 3):
print(list(group))
which does indeed do what I want:
python group.py
['a', 'b', 'c']
['d', 'e', 'f']
['g', 'h']
Is there something better/cleaner?
Yeah, I know, this fails if any item is not truthy, but assume that's not a problem.