itertools.product
Iterate over all combinations of items from several collections.
Python 3.13
itertools.product(*iterables, repeat=1)Parameters
- *iterablesIterable
- The collections to take items from.
- repeatintoptional
- How many times to repeat the collections, such as product("01", repeat=3).
Return value
An iterator of tuples.
Examples
All pairs from two collections
Python 3.13
from itertools import product
print(list(product('ab', [1, 2])))[('a', 1), ('a', 2), ('b', 1), ('b', 2)]All binary strings of length 3
Python 3.13
from itertools import product
print([''.join(bits) for bits in product('01', repeat=3)])['000', '001', '010', '011', '100', '101', '110', '111']
Details
It replaces nested loops: product(a, b) goes through pairs in the same order as for x in a: for y in b. The number of combinations is the product of the lengths, so it grows quickly.
