easy +10 pts

Batch Iterator

Yield successive fixed-size chunks from an iterable without missing the last partial batch.

Create a generator function named `batch_iterator` that takes an iterable of items and a positive integer `batch_size`, and yields lists of items in successive batches of the given size. Each batch should contain at most `batch_size` items. The last batch will contain fewer if the total number of items is not evenly divisible by `batch_size`. Your generator must: - Accept any iterable (list, tuple, string, generator, etc.). - Yield lists, not tuples. - Handle `batch_size` equal to 1 (each batch contains a single item). - Handle an empty iterable (yields nothing). Signature: `def batch_iterator(iterable, batch_size):`

Constraints

- `batch_size` is a positive integer (>= 1). - The iterable may be empty. - The function returns a generator object (lazy evaluation). - Complexity: O(n) time and O(batch_size) auxiliary space.

Example

>>> list(batch_iterator([1, 2, 3, 4, 5], 2))
[[1, 2], [3, 4], [5]]
>>> list(batch_iterator('abcdef', 3))
[['a', 'b', 'c'], ['d', 'e', 'f']]
>>> list(batch_iterator([], 5))
[]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Convert the iterable to an iterator so you can pull items lazily with `next()`.
Loop while you can grab at least one item; use a list to collect a batch.
A try/except StopIteration can handle the last partial batch cleanly.
Build each batch incrementally and yield it as soon as you have `batch_size` items or the source exhausts.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.