Batch an Iterator Lazily
Consume an iterable in fixed-size batches with a generator, processing large streams without loading everything into memory.
Code
from typing import Iterable, Iterator, List, TypeVar
T = TypeVar("T")
def batched(items: Iterable[T], size: int) -> Iterator[List[T]]:
if size <= 0:
raise ValueError("size must be positive")
batch: List[T] = []
for item in items:
batch.append(item)
if len(batch) == size:
yield batch
batch = []
if batch:
yield batch
for group in batched(range(7), 3):
print(group)Output
Captured from a sandboxed run of this snippet in the build pipeline.
[0, 1, 2]
[3, 4, 5]
[6]How it works
Count the function batched as the entire surface area of Batch an Iterator Lazily.
Iteration happens inside for item in items — everything outside it runs once. ValueError is the guard’s signal — thrown at the branch, before any partial work happens.
What to watch for
- The guard
size <= 0short-circuits the flow with an earlyraisewhen its condition holds.
Using it
The main signature reads def batched(items: Iterable[T], size: int) -> Iterator[List[T]]
The surface worth importing is batched; the helpers around it are private to the snippet.
Key statements
def batched(items: Iterable[T], size: int) -> Iterator[List[T]]:
if size <= 0:
raise ValueError("size must be positive")
batch: List[T] = []
for item in items:
batch.append(item)
if len(batch) == size:
yield batch
batch = []
if batch:
yield batch
Interactive Tools for This Topic
FAQ
- Does the code validate its input?
- The code throws `ValueError` — the guard `size <= 0` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. Every import resolves inside the standard library — `typing`. The file defines `batched` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.