Skip to content

Instantly share code, notes, and snippets.

@blackrobot
Last active December 29, 2017 22:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blackrobot/c7a7627d3cb0bb9a83166ab2f5e148c1 to your computer and use it in GitHub Desktop.
Save blackrobot/c7a7627d3cb0bb9a83166ab2f5e148c1 to your computer and use it in GitHub Desktop.
from __future__ import print_function, unicode_literals
from six import itertools
def batch(iterable, size):
""" Generates slices of items in groups of `size` length.
>>> for group in batch(range(10), size=4):
print(group)
(0, 1, 2, 3)
(4, 5, 6, 7)
(8, 9)
"""
sentinel = object()
items = itertools.repeat(iter(iterable), size)
for group in itertools.izip_longest(*items, fillvalue=sentinel):
yield tuple(
item for item in group if item is not sentinel
)
@blackrobot
Copy link
Author

This is based off of implementations I found:

If the size of each chunk is set very high, this should be altered to yield a generator instead of a tuple. But this isn't necessary if size < 10 ** 6.

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