How to Compute the Cartesian Product of Two Lists in Python
Generates all ordered pairs from two lists using itertools.product and prints each combination.
Python code
13 linesfrom itertools import product
# Two small input lists
list_a = [1, 2, 3]
list_b = ["x", "y"]
# Compute the Cartesian product
result = list(product(list_a, list_b))
# Display the result
print("Cartesian product of", list_a, "and", list_b, "is:")
for pair in result:
print(pair)
Output
Cartesian product of [1, 2, 3] and ['x', 'y'] is:
(1, 'x')
(1, 'y')
(2, 'x')
(2, 'y')
(3, 'x')
(3, 'y')
How it works
The itertools.product function returns an iterator that yields tuples, each containing one element from list_a followed by one from list_b. Wrapping it in list() materializes all pairs into a list. The order follows the input sequences: for each element in list_a, it iterates through all elements in list_b. This provides a concise and efficient way to generate combinatorial pairings without nested loops.
Common mistakes
- Forgetting to wrap `product` in `list()` when you need all pairs at once, since it returns an iterator.
- Assuming the order of pairs follows list_b first; product yields elements from the first iterable as the first tuple element.
- Using nested for loops unnecessarily, which is longer and less readable than `itertools.product`.
Variations
- Use a nested list comprehension: `[(a, b) for a in list_a for b in list_b]`
- Compute the product of an arbitrary number of iterables by passing multiple arguments to `product`.
Real-world use cases
- Generating all possible test combinations for parameterized testing in CI pipelines.
- Creating pairing grids for A/B testing by crossing user groups with feature variants.
- Building coordinate pairs when mapping grid positions in data visualizations or simulations.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.