Batch an Iterator into Fixed-Size Chunks

Group any iterable into fixed-size lists lazily, preserve the final partial batch, and stop cleanly when the source is exhausted.

PythonData Fetching

Code

pythonsnippet
35 lines
from collections.abc import Iterable, Iterator
from itertools import islice
from typing import TypeVar

T = TypeVar("T")


def chunked(items: Iterable[T], size: int) -> Iterator[list[T]]:
    if size < 1:
        raise ValueError("size must be at least 1")

    iterator = iter(items)
    while True:
        batch = list(islice(iterator, size))
        if not batch:
            return
        yield batch


def main() -> None:
    for batch in chunked(range(1, 11), 3):
        print(batch)

    print(list(chunked([], 2)))
    print(list(chunked((value for value in range(3)), 5)))

    try:
        list(chunked(range(5), 0))
    except ValueError as error:
        print("error:", error)


if __name__ == "__main__":
    main()

How the snippet works

Batch an Iterator into Fixed-Size Chunks is built around the functions chunked and main.

Iteration happens inside while True — everything outside it runs once. ValueError is the guard’s signal — thrown at the branch, before any partial work happens.

Watch out for

  • The guard size < 1 short-circuits the flow with an early raise when its condition holds.

Applying it

Entry signature: def chunked(items: Iterable[T], size: int) -> Iterator[list[T]]

The run prints error: — each prefix names the step that produced it.

main sequences chunked; executing the file runs that flow once.

Statements that matter

def main() -> None:
    for batch in chunked(range(1, 11), 3):
        print(batch)
    print(list(chunked([], 2)))
    print(list(chunked((value for value in range(3)), 5)))
    try:
        list(chunked(range(5), 0))
    except ValueError as error:
        print("error:", error)
def chunked(items: Iterable[T], size: int) -> Iterator[list[T]]:
    if size < 1:
        raise ValueError("size must be at least 1")
    iterator = iter(items)
    while True:
        batch = list(islice(iterator, size))
        if not batch:
            return
        yield batch

Interactive Tools for This Topic

FAQ

What happens on invalid input?
The code refuses to continue: `ValueError` is thrown while the state is still recoverable.
What does Batch an Iterator into Fixed-Size Chunks print when run?
Running the file directly is enough — expect labeled output lines such as `error:`.