Created
October 17, 2016 20:41
-
-
Save dslaw/2ad17ac2011d447181bcc889446553bf to your computer and use it in GitHub Desktop.
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 chunk(xs, n): | |
""" Split an iterable into chunks. | |
Parameters | |
---------- | |
xs : iterable | |
Iterable to be split. | |
n : int | |
Chunk size. | |
Returns | |
------- | |
generator | |
""" | |
sublist = [] | |
for x in xs: | |
sublist.append(x) | |
if len(sublist) == n: | |
yield sublist | |
sublist = [] | |
else: | |
# Yield leftover item(s) when input collection | |
# is exhausted, if any exist. | |
if sublist: | |
yield sublist |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment