I am getting the hang of the grouper()
recipe from itertools
:
def grouper(iterable, n, fillvalue=None):
"Collect data into fixed-length chunks or blocks"
# grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
This version fills the last group with a given value. If I remove fillvalue
, then it does not return the last group if it has less than n
elements. I have encountered several situations where I want the last group whether or not it is the same size as all the other groups. I also do not want to add any padding. How do I go about doing this?
I usually use
islice
:If you prefer, the following is just a slight change in the logic, but it works the same:
There are other variants here too. For example, if you want a completely lazy version:
This is likely less performant than
islice
since it does so much calling back into python, but it is completely lazy (and safe). e.g. it yields iterators over groups and it handles the case where the caller doesn't consume every element in a group iterator.