Skip to content

Instantly share code, notes, and snippets.

@ZekunZh
Created February 16, 2022 10:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ZekunZh/7b2dac1df61f1ba1f4262ab4ceabee5d to your computer and use it in GitHub Desktop.
Save ZekunZh/7b2dac1df61f1ba1f4262ab4ceabee5d to your computer and use it in GitHub Desktop.
def iter_batches(iterable, batch_size):
"""Iterates over the given iterable in batches.
Args:
iterable: an iterable
batch_size: the desired batch size, or None to return the contents in
a single batch
Returns:
a generator that emits tuples of elements of the requested batch size
from the input
"""
it = iter(iterable)
while True:
chunk = tuple(itertools.islice(it, batch_size))
if not chunk:
return
yield chunk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment