batched(iterable, size) yielding lists of up to size items — accumulating a buffer, yielding when full, and yielding the final partial batch if any. Works on any iterable, including other generators, without materializing the whole input.list(batched(range(5), 2))
[[0, 1], [2, 3], [4]]
Two full batches and a remainder.
Append to a buffer; yield and reset at size.
After the loop, yield the leftovers if non-empty.