Skip to content

Instantly share code, notes, and snippets.

@Goldziher
Created November 10, 2021 13:32
Show Gist options
  • Save Goldziher/d49b6f07802f6c32f4f0aac01961e0c7 to your computer and use it in GitHub Desktop.
Save Goldziher/d49b6f07802f6c32f4f0aac01961e0c7 to your computer and use it in GitHub Desktop.
generic python chunk function
from itertools import islice
from typing import Iterator, Sequence, TypeVar
T = TypeVar("T")
def chunk(sequence: Sequence[T], size: int) -> Iterator[list[T]]:
"""given a sequence, return an iterator of lists of the given size"""
return iter(lambda: list(islice(iter(sequence), size)), [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment