How to Create an Iterator That Interleaves Elements from Iterable Objects

When working with multiple data sources or sequences, we sometimes need to interleave their elements — for example, by combining readings from several sensors in time order, distributing tasks evenly among workers, or blending separate data lists for a report or visualization.
An iterator that interleaves elements lets you handle round-robin–style processing naturally and efficiently, without building large intermediate structures or writing complex loops.

To make this more concrete, imagine a few simple scenarios:

  • You have three sensors — measuring temperature, pressure, and humidity — each producing a sequence of readings. Interleaving their data allows you to process the values in real time, one from each source at a time.
  • You’re preparing a performance report and want to weave together data from several machines so that each contributes its next measurement in turn.
  • You want to distribute tasks evenly among several workers or devices — cycling through them one by one, assigning a new job each time.

In all these cases, an interleaving iterator provides a clean and Pythonic solution.

In this post, you’ll see how to build an iterator that interleaves elements from multiple iterable objects — that is, it yields one element from each in turn, cycling through them until one of them runs out.

Suppose we have three strings: ‘ABC’, ‘DEF’, and ‘GHI’. The iterator should then produce the sequence:

‘A’, ‘D’, ‘G’, ‘B’, ‘E’, ‘H’, ‘C’, ‘F’, ‘I’.

There are several ways to implement this behavior. The key idea in each case is the same:

  1. First, create iterators from the input iterables using the built-in iter() function.
  2. Store those iterators in the same order as the input sequences, so we can rotate through them in turn.
  3. Then build the logic that repeatedly retrieves the next element from each iterator, cycling until one of them is exhausted.

The implementations differ mainly in how this cyclic retrieval is handled.

Below you can find a few possible implementations, each with explanatory comments.
The first defines a dedicated iterator class, the next two are generator functions, and the last one returns an iterator directly.
As you can see, the last version is by far the most compact.

Most of these implementations use the itertools module from the Python standard library.
In fact, as a general rule, whenever your task involves creating or manipulating iterators, it’s worth exploring what itertools has to offer. It can greatly simplify your code and make it both more readable and more expressive.

You can find a more detailed discussion of the available iterators in the itertools module, with plenty of examples, in the chapter “Special Iterators” of the e-book Python Knowledge Building Step by Step.

Interested in the e-book Python Knowledge Building Step by Step: From the Basics to Your First Desktop Application?