Skip to content

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 1itertools.islice(it, n) takes the next n items of an iterator.
Hint 2Call iter(iterable) once, then keep slicing the same iterator.
Hint 3Stop when a slice comes back empty.

Learn the concepts

More Python problems

All Python problems