How to Use itertools.product in Python: Syntax and Examples
Use
itertools.product in Python to get the Cartesian product of input iterables, which means all possible pairs or tuples combining elements from each iterable. Import it with from itertools import product and call product(iterable1, iterable2, ...) to generate combinations.Syntax
The itertools.product function syntax is:
product(*iterables, repeat=1)
Here:
*iterablesmeans you can pass one or more lists, strings, or other iterable objects.repeatis an optional number that repeats the input iterable that many times.
python
from itertools import product # Basic syntax product(iterable1, iterable2, ..., repeat=1)
Example
This example shows how to get all pairs from two lists using itertools.product. It prints every combination of one element from the first list with one from the second.
python
from itertools import product colors = ['red', 'green'] sizes = ['S', 'M'] for combo in product(colors, sizes): print(combo)
Output
('red', 'S')
('red', 'M')
('green', 'S')
('green', 'M')
Common Pitfalls
Common mistakes include:
- Forgetting to import
productfromitertools. - Passing non-iterable arguments, which causes errors.
- Not understanding that
productreturns an iterator, so you need to loop over it or convert it to a list. - Misusing the
repeatargument by passing it without keyword, which can cause confusion.
python
from itertools import product # Wrong: missing import # combos = product(['a', 'b'], ['1', '2']) # NameError # Wrong: passing non-iterable # combos = product(5, ['x', 'y']) # TypeError # Right: convert to list to see all combos combos = list(product(['a', 'b'], ['1', '2'])) print(combos) # Using repeat keyword combos_repeat = list(product(['a', 'b'], repeat=2)) print(combos_repeat)
Output
[('a', '1'), ('a', '2'), ('b', '1'), ('b', '2')]
[('a', 'a'), ('a', 'b'), ('b', 'a'), ('b', 'b')]
Quick Reference
Summary tips for itertools.product:
- Use it to get all combinations of multiple iterables.
- It returns an iterator, so loop or convert to list to access results.
- The
repeatargument repeats the input iterable multiple times. - Works with any iterable: lists, strings, tuples, etc.
Key Takeaways
Import
product from itertools to use it.product generates all possible tuples combining elements from input iterables.Remember
product returns an iterator; convert to list or loop to access items.Use the
repeat argument to repeat the same iterable multiple times.Pass only iterable objects to avoid errors.