Skip to content

Instantly share code, notes, and snippets.

@willist
Last active December 15, 2015 13:09
Show Gist options
  • Save willist/5265502 to your computer and use it in GitHub Desktop.
Save willist/5265502 to your computer and use it in GitHub Desktop.
Chunkify your iterable.
"""
Chunk a sequence similar to the itertools grouper recipe, but without the filler.
>>> list(chunky(range(10), 0))
[]
>>> list(chunky(range(10), 1))
[(0,), (1,), (2,), (3,), (4,), (5,), (6,), (7,), (8,), (9,)]
>>> list(chunky(range(10), 5))
[(0, 1, 2, 3, 4), (5, 6, 7, 8, 9)]
>>> list(chunky(range(10), 10))
[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)]
"""
from itertools import islice
def chunky(sequence, n=None):
iterable = iter(sequence)
next_group = tuple(islice(iterable, n))
while next_group:
yield next_group
next_group = tuple(islice(iterable, n))
if __name__ == "__main__":
import doctest
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment