itertools.chain
Iterate over the items of several collections in a row, as one.
Python 3.13
itertools.chain(*iterables)Parameters
- *iterablesIterable
- The collections that follow each other.
Return value
An iterator over the items of all collections in turn.
Examples
A list, a tuple and a string in a row
Python 3.13
from itertools import chain
print(list(chain([1, 2], (3,), 'ab')))[1, 2, 3, 'a', 'b']
Flattening a list of lists
Python 3.13
from itertools import chain
print(list(chain.from_iterable([[1, 2], [3], []])))[1, 2, 3]
Details
Unlike adding lists a + b, it does not create a new list and works with any iterables. To join a list of lists, use chain.from_iterable(lists).
