Skip to content

Instantly share code, notes, and snippets.

@dslaw
Created October 17, 2016 20:41
Show Gist options
  • Save dslaw/2ad17ac2011d447181bcc889446553bf to your computer and use it in GitHub Desktop.
Save dslaw/2ad17ac2011d447181bcc889446553bf to your computer and use it in GitHub Desktop.
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