On this page
itertools.product
Prev: itertools.permutations | Up: itertools | Next: itertools.repeat
Rel: itertools.accumulate, itertools.batched, itertools.chain, itertools.combinations
Ref: docs.python.org — itertools.product
Tags: #public #python3 #stdlib #itertools
Import
import itertools
from itertools import product
Signature & Overview
itertools.product(*iterables, repeat=1)
Cartesian product of input iterables. Equivalent to nested for-loops.
Usage
from itertools import product
assert list(product("AB", [1, 2])) == [("A", 1), ("A", 2), ("B", 1), ("B", 2)]
# repeat= produces the Cartesian power (like nested loops over the same iterable)
assert list(product([0, 1], repeat=2)) == [(0, 0), (0, 1), (1, 0), (1, 1)]
Gotchas
- Materializes inputs up front:
product()converts each input iterable to a tuple internally, so it cannot take infinite iterators likecount(). - Replaces deeply nested
forloops: Cleaner and supports a dynamic number of iterables viaproduct(*iterables).
REPL Inspect
from itertools import product
help(product)
Linked from
Related notes
- tuts/python3/stdlib_module/itertools/permutations Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/repeat Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/accumulate Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/batched Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/chain Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations Linked here; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations_with_replacement shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/compress shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/count shared tags: #itertools, #stdlib