Skip to content

Instantly share code, notes, and snippets.

@nwjlyons
Created December 6, 2017 10:26
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nwjlyons/621fabfc0d4c1119b2ad338f615ce4ef to your computer and use it in GitHub Desktop.
Save nwjlyons/621fabfc0d4c1119b2ad338f615ce4ef to your computer and use it in GitHub Desktop.
Python split generator into sub lists
def chunks(generator, chunk_size):
"""Yield successive chunks from a generator"""
chunk = []
for item in generator:
if len(chunk) >= chunk_size:
yield chunk
chunk = [item]
else:
chunk.append(item)
if chunk:
yield chunk
@nwjlyons
Copy link
Author

nwjlyons commented Dec 6, 2017

eg.

>>> for chunk in chunks(range(10), 4):
...       print(chunk)
...
[0, 1, 2, 3]
[4, 5, 6, 7]
[8, 9]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment