Skip to content

Instantly share code, notes, and snippets.

@bdsaglam
Last active September 23, 2019 09:39
Show Gist options
  • Save bdsaglam/9943e98efe53524b37ff9812c8deeaea to your computer and use it in GitHub Desktop.
Save bdsaglam/9943e98efe53524b37ff9812c8deeaea to your computer and use it in GitHub Desktop.
Iterate by batches
def batch(iterable, size, drop_remainder=False):
if size < 1:
raise ValueError("size must be greater than zero.")
iterator = iter(iterable)
while True:
try:
items = []
for _ in range(size):
items.append(next(iterator))
except StopIteration:
if len(items)==0 or drop_remainder:
return None
yield items
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment