Editor

Interleave Streams

#92 · Iterators and generators · Intermediate · 75 XP · about 14 min

Write a generator interleave(*iterables) that takes any number of iterables and yields their items in turns: the first item of each, in order, then the second item of each, and so on. When one runs out, skip it and keep taking turns among the rest until all of them are used up.

It must be lazy: it takes an item from a source only when that item is needed, so it also works when some sources never end.

Examples

list(interleave([1, 2, 3], 'ab'))            # returns [1, 'a', 2, 'b', 3]
list(interleave('AB', [], 'xyz'))            # returns ['A', 'x', 'B', 'y', 'z']
list(interleave())                           # returns []

from itertools import count, islice
list(islice(interleave(count(), 'hi'), 6))   # returns [0, 'h', 1, 'i', 2, 3]

Constraints

  • Up to 100 sources, each with up to 10,000 items, or endless
  • Items can be any values, including None

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.