Skip to content

Instantly share code, notes, and snippets.

@davidwtbuxton
Last active August 10, 2017 23:27
Show Gist options
  • Save davidwtbuxton/2e405de65e863a999f2d03e037052c97 to your computer and use it in GitHub Desktop.
Save davidwtbuxton/2e405de65e863a999f2d03e037052c97 to your computer and use it in GitHub Desktop.
Like itertools.grouper but the last group doesn't have padding
import itertools
def grouper(iterable, n):
"""Collect data into chunks.
This is different to the grouper recipe in itertools in that the final
chunk may be shorter.
>>> grouper('ABCDEF', 3)
<generator object grouper at 0x11007a6e0>
>>> tuple(grouper('ABCDEF', 3))
(['A', 'B', 'C'], ['D', 'E', 'F'])
>>> tuple(grouper('ABCD', 3))
(['A', 'B', 'C'], ['D'])
"""
iterator = iter(iterable)
chunk = list(itertools.islice(iterator, n))
while chunk:
yield chunk
chunk = list(itertools.islice(iterator, n))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment