all Python 3Iterators & generatorsterm
itertools.chain
itertools
Walks through several iterables one after another as if they were a single one.
Syntax
from itertools import chain
chain(a, b, c)
Unlike a + b, chain copies nothing: items are pulled one at a time as you iterate, memory stays constant, and it accepts any iterables — sets, files, generators — not just lists of one type. The gap between chain(*matrix) and chain.from_iterable(matrix) matters: the star expands the outer sequence into arguments immediately, while from_iterable consumes it lazily and therefore survives very long or endless outer sources. What you get back is an ordinary single-pass iterator, so there is no second walk over it.
Examples
from itertools import chain
result = list(chain([1,2],[3,4],[5,6]))
print(result) # → [1,2,3,4,5,6]
from itertools import chain
# chain.from_iterable
matrix = [[1,2],[3,4],[5,6]]
flat = list(chain.from_iterable(matrix))
print(flat) # → [1,2,3,4,5,6]
from itertools import chain
# Объединение строк
words = list(chain('hello', ' ', 'world'))
print(''.join(words)) # → hello world
from itertools import chain
# С генераторами
def gen1(): yield 1; yield 2
def gen2(): yield 3; yield 4
print(list(chain(gen1(), gen2()))) # → [1,2,3,4]
from itertools import chain
# chain vs list + list
a = range(1000000); b = range(1000000)
from itertools import chain
# chain(a,b) — без создания списка в памяти!
See also
Open in the full glossarydocs.python.orgReport an inaccuracy