Chunk a Stream
Write a generator chunked(iterable, size) that yields lists of size items taken from iterable, in order. The last list may be shorter. It must work for any iterable, including a generator, which has no len and cannot be sliced, and it must be lazy: take only as many items as the current chunk needs.
If size is less than 1, raise ValueError when the first chunk is asked for.
Understand the problem
What a generator source can and cannot do.
Which of these works on a generator g?
len(g)g[0:3]next(g)
A generator has no length and cannot be indexed or sliced: you can only take the next item. So the problem must be solved with next or a for loop, not with positions.
itertools.islice(it, 3) does what?
- Takes a slice of a list
- Takes up to the next 3 items from an iterator, lazily
- Skips 3 items
islice works on any iterator and consumes only the items it returns. It is the slicing tool for iterators, and the key to this problem.
Write the solution
A generator function that yields lists.
def chunked(iterable, size):
# Write your code here.
pass
Hint 1: a question to ask yourself
How can you take the next size items from an iterator, and how do you know you have reached the end?
Hint 2: the shape of the answer
it = iter(iterable). Loop: chunk = list(islice(it, size)); if the chunk is empty, stop; otherwise yield chunk. Check size first.
Reflect
Solution
from itertools import islice
def chunked(iterable, size):
if size < 1:
raise ValueError("size must be at least 1")
iterator = iter(iterable)
while True:
chunk = list(islice(iterator, size))
if not chunk:
return
yield chunk
Another way: the walrus operator
from itertools import islice
def chunked(iterable, size):
if size < 1:
raise ValueError("size must be at least 1")
iterator = iter(iterable)
while chunk := list(islice(iterator, size)):
yield chunk
What this tests: generators, iter, islice, laziness, the walrus operator (:=) and thinking in streams instead of lists.
Why iter(iterable) first: a list is an iterable but not an iterator. iter() gives an iterator that remembers its position, so each islice continues where the last one stopped. For a generator, iter(g) is g itself.
Why the error comes when the first chunk is requested: the body of a generator function does not run until the first next(). That is how generators work, and it is the behaviour the task asks for.
Laziness matters: reading a 100 GB file in chunks of 10,000 lines must not load the file. This function reads exactly one chunk at a time. Python 3.12 has itertools.batched for this.
Cost: O(n) time, O(size) memory.
What an interviewer might ask next: Yield tuples instead of lists, as itertools.batched does. (tuple(islice(...)).)
VISIBLE = 3
CASES = [
('result = list(chunked([1, 2, 3, 4, 5], 2))', [[1, 2], [3, 4], [5]], 'a list'),
('result = list(chunked(iter(range(7)), 3))', [[0, 1, 2], [3, 4, 5], [6]], 'an iterator, which cannot be sliced'),
('result = list(chunked([], 3))', [], 'nothing to chunk'),
('result = list(chunked("abcde", 2))', [['a', 'b'], ['c', 'd'], ['e']], 'a string'),
('consumed = []\ndef source():\n for i in range(10):\n consumed.append(i)\n yield i\ng = chunked(source(), 3)\nnext(g)\nresult = len(consumed)', 3, 'it is lazy: only one chunk is read'),
('result = error_of(lambda: next(chunked([1, 2], 0)))', 'ValueError', 'a size of zero is an error'),
('result = list(chunked(range(4), 4))', [[0, 1, 2, 3]], 'one exact chunk'),
('result = type(chunked([1], 1)).__name__', 'generator', 'it is a generator'),
]