Skip to content

Instantly share code, notes, and snippets.

@jdowner
Created February 2, 2015 12:28
Show Gist options
  • Save jdowner/bd99a4fd2677539d2706 to your computer and use it in GitHub Desktop.
Save jdowner/bd99a4fd2677539d2706 to your computer and use it in GitHub Desktop.
Iterator to return a sequence of blocks from an iterable
def blocks(iterable, n):
"""Create a generator that returns blocks of values
This generator yields lists of values from the iterable that contain 'n'
elements (except, possible, for the last block if the length of the iterable
is not divisible by 'n').
Arguments:
iterable: an interable object like a list or generator
n: a positive integer
"""
iterator = iter(iterable)
while True:
try:
block = []
for _ in range(n):
block.append(iterator.next())
finally:
yield block
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment