Skip to content

Instantly share code, notes, and snippets.

@rafalkrupinski
Created January 16, 2023 19:50
Show Gist options
  • Save rafalkrupinski/31fa1e9f2eeb6eb3ad3ca6698349efa2 to your computer and use it in GitHub Desktop.
Save rafalkrupinski/31fa1e9f2eeb6eb3ad3ca6698349efa2 to your computer and use it in GitHub Desktop.
Create chunks of given size out of an iterator
def iter_chunks(iter: Iterator[T], size: int) -> Iterator[Iterable[T]]:
"""Create chunks of given size out of an iterator"""
chunk: list[T] = []
for idx, elem in enumerate(iter):
chunk.append(elem)
if idx + 1 % size == 0:
yield chunk
chunk = []
if chunk:
yield chunk
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment