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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 15 views 0 copies

Python code

13 lines
Python 3.9+
from 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

stdout
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

  1. Use a nested list comprehension: `[(a, b) for a in list_a for b in list_b]`
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.