Can you think of a nice way (maybe with itertools) to split an iterator into chunks of given size?
Therefore l=[1,2,3,4,5,6,7] with chunks(l,3) becomes an iterator [1,2,3], [4,5,6], [7]
I can think of a small program to do that but not a nice way with maybe itertools.
The
grouper()recipe from theitertoolsdocumentation’s recipes comes close to what you want:This won’t work well when the last chunk is incomplete though, as, depending on the
incompletemode, it will either fill up the last chunk with a fill value, raise an exception, or silently drop the incomplete chunk.In more recent versions of the recipes they added the
batchedrecipe that does exactly what you want:Finally, a less general solution that only works on sequences but does handle the last chunk as desired and preserves the type of the original sequence is:
Since python 3.12, you can also just use
itertools.batched. From docs: