Skip to content
GreenSnippets

Split any iterable into batches

Yield fixed-size lists from a list, generator or file without loading everything into memory.

from itertools import islice


def batched(iterable, size):
    if size < 1:
        raise ValueError("size must be >= 1")
    iterator = iter(iterable)
    while batch := list(islice(iterator, size)):
        yield batch

Output

list(batched(range(5), 2))  # [[0, 1], [2, 3], [4]]

How it works

Python 3.12 adds itertools.batched; this version works on older interpreters and returns lists. Because it consumes the iterable lazily, you can batch a huge file or database cursor while holding only one batch in memory.