PythiloLesson 3 of 8 · progress kept in this browser

Batch an iterator without losing the tail

Batching reduces overhead, but a final short batch must not disappear. An iterator may be consumed only once, so accumulate at most one batch at a time. Yielding the current list and then allocating a fresh one avoids changing batches the caller already received. Reject a zero batch size instead of looping forever.

from itertools import islice
source = iter(range(5))
print(list(islice(source, 2)))
Your task

Write chunks(values, size) as a generator of lists, each containing at most size items. Keep the final partial batch. For size <= 0, iteration must raise ValueError.