Write a generator that yields an input sequence in fixed-size chunks without building all chunks up front.
Answer
For a sequence that supports slicing, iterate start indexes in steps of the chunk size and `yield` one slice at a time. Because the function yields instead of returning a complete list of slices, callers can consume each chunk incrementally. Validate that the chunk size is positive so invalid input fails explicitly instead of producing confusing behavior.
Strong answer includes
- uses yield to produce chunks lazily
- advances indexes by the chunk size
- validates a positive chunk size
Practical example
Python
Result
Run the code to see the result.
The generator holds only its current execution state; each slice is created when the caller asks for the next chunk.
Expected result: [[1, 2], [3, 4], [5]]