Created
February 2, 2015 12:28
-
-
Save jdowner/bd99a4fd2677539d2706 to your computer and use it in GitHub Desktop.
Iterator to return a sequence of blocks from an iterable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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