22. Batch an Iterable
Difficulty: Easy · Topic: Generators & iterators
Bulk APIs take rows in groups. Write a generator batch(iterable, n) that yields lists of n consecutive items; the last list may be shorter. Never yield an empty list.
The input can be endless (a stream), so take items one batch at a time.
Your code runs in CPython on our servers against 5 tests, including hidden ones.
Sample test
list(batch(range(7), 3))Expected: [[0, 1, 2], [3, 4, 5], [6]]
Hints
Hint 1
itertools.islice(it, n) takes the next n items of an iterator.Hint 2
Calliter(iterable) once, then keep slicing the same iterator.Hint 3
Stop when a slice comes back empty.Learn the concepts
- Generators and lazy evaluation · 6 min read. yield, constant-memory pipelines, endless inputs and the one-pass rule.
More Python problems
- Read a File in Chunks · Easy
- A Generator Pipeline · Medium
- Moving Average over a Stream · Medium
- Flatten Any Iterable Lazily · Medium
- A Re-iterable Date Range · Medium
- Merge Sorted Streams Lazily · Hard