Hard: Advanced Interview · Problem 71 of 82

Interleave Iterables

HardGenerators and IteratorsPython

Write a generator interleave(*iterables) that yields one item from each iterable in turn (a round-robin), skipping iterables that have run out, until all are exhausted.

list(interleave([1, 2, 3], "ab", [10])) is [1, "a", 10, 2, "b", 3]. With no iterables it yields nothing.

Understand the problem

Look at how zip behaves and what it lacks.

What does list(zip([1, 2, 3], "ab")) give?

  1. [(1, "a"), (2, "b"), (3, None)]
  2. [(1, "a"), (2, "b")]
  3. An error

zip stops at the shortest input. The 3 is silently dropped. For a round-robin that must continue, you need something that keeps going while any input still has items.

What does next(it, None) do when the iterator it is exhausted?

  1. Raises StopIteration
  2. Returns None instead of raising
  3. Restarts the iterator

The second argument is a default returned instead of raising StopIteration. A unique marker object (not None) is safer as the default if None can be a real item.

Write the solution

A generator function that takes any number of iterables.

def interleave(*iterables):
    # Write your code here.
    pass
Hint 1: a question to ask yourself

How do you keep going through the iterables in turns, and how do you drop one when it is finished?

Hint 2: the shape of the answer

Make iterators with iter(). Loop while the list of iterators is not empty. For each one, try next; if it raises StopIteration, remove it, otherwise yield the value.

Reflect

Solution

def interleave(*iterables):
    iterators = [iter(it) for it in iterables]
    while iterators:
        still_going = []
        for iterator in iterators:
            try:
                value = next(iterator)
            except StopIteration:
                continue
            yield value
            still_going.append(iterator)
        iterators = still_going

Another way: zip_longest with a marker

from itertools import zip_longest

_MISSING = object()

def interleave(*iterables):
    for group in zip_longest(*iterables, fillvalue=_MISSING):
        for value in group:
            if value is not _MISSING:
                yield value

What this tests: iterators and StopIteration, next with and without a default, a generator that manages several iterators, and zip_longest.

The marker object: zip_longest pads short inputs with fillvalue. If you pad with None, an input that really contains None cannot be told apart from padding. A private object() is never equal to anything else, so it is a safe marker.

StopIteration is how iteration ends. A for loop catches it for you. When you call next yourself, you must handle it (or give a default).

Cost: O(total items), lazy, O(number of iterables) memory.

What an interviewer might ask next: This is the roundrobin recipe from the itertools documentation. Can you write it with itertools.cycle and islice? (It is a famous, tricky one-liner.)