all Python 3itertoolsfunction
itertools.product
itertools
Cartesian product of iterables (nested loops as a flat iterator).
Syntax
itertools.product(*iterables, repeat=1)
product flattens nested for-loops into one iterator, but it fully materializes every input into memory first — so an infinite or huge iterable will hang or exhaust RAM. The rightmost argument varies fastest, and repeat=N gives the product of a set with itself N times instead of an N-deep loop nest.
Examples
import itertools
print(list(itertools.product([1, 2], ['a', 'b']))) # → [(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]
print(list(itertools.product('ab', repeat=2))) # → [('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]
print([''.join(p) for p in itertools.product('01', repeat=3)]) # → ['000', '001', '010', '011', '100', '101', '110', '111']
print(len(list(itertools.product(range(3), range(4))))) # → 12
print(list(itertools.product([1, 2], []))) # → []
See also
Open in the full glossarydocs.python.orgReport an inaccuracy