Skip to content

Instantly share code, notes, and snippets.

@ValentinMouret
Created October 27, 2021 13:48
Show Gist options
  • Save ValentinMouret/fa72e61b8d42b9507a724759382116d9 to your computer and use it in GitHub Desktop.
Save ValentinMouret/fa72e61b8d42b9507a724759382116d9 to your computer and use it in GitHub Desktop.
from typing import Any, Iterable, List
def partition(coll: Iterable[Any], size: int, use_padding=False) -> Iterable[Any]:
"""Lazily partition the iterable by making batches of size `size`.
Arguments:
* coll: iterable to partition
* size: size of the desired partitions
* use_padding: whether to use padding for the last batch in case it’s smaller
than the desired size. The default behaviour is to use no padding.
"""
batch: List[Any] = []
for item in coll:
if len(batch) == size:
yield tuple(batch)
batch = []
batch.append(item)
if batch:
last_batch = batch if not use_padding else batch + [None] * (len(batch) - size)
yield tuple(last_batch)
return
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment