batched_chunks over lazy iterables
Python
"""Split any iterable into fixed-size lists without materialising it first."""
from collections.abc import Iterable, Iterator
from itertools import islice
from typing import TypeVar
T = TypeVar("T")
def batched_chunks(iterable: Iterable[T], size: int) -> Iterator[list[T]]:
"""Yield lists of at most size items; the final batch may be shorter."""
if size < 1:
raise ValueError("size must be at least 1")
source = iter(iterable)
while batch := list(islice(source, size)):
yield batch
if __name__ == "__main__":
print(list(batched_chunks(range(7), 3))) # [[0, 1, 2], [3, 4, 5], [6]]
print(list(batched_chunks("abcde", 2))) # [['a', 'b'], ['c', 'd'], ['e']]