Python Language Itertools Module Chaining multiple iterators together


Use itertools.chain to create a single generator which will yield the values from several generators in sequence.

from itertools import chain
a = (x for x in ['1', '2', '3', '4'])
b = (x for x in ['x', 'y', 'z'])
' '.join(chain(a, b))

Results in:

'1 2 3 4 x y z'

As an alternate constructor, you can use the classmethod chain.from_iterable which takes as its single parameter an iterable of iterables. To get the same result as above:

' '.join(chain.from_iterable([a,b])

While chain can take an arbitrary number of arguments, chain.from_iterable is the only way to chain an infinite number of iterables.