Hard: Advanced Interview · Problem 69 of 82

Chunk a Stream

HardGenerators and IteratorsPython

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?

  1. len(g)
  2. g[0:3]
  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?

  1. Takes a slice of a list
  2. Takes up to the next 3 items from an iterator, lazily
  3. 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(...)).)