Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find Cartesian product of two lists
The Cartesian product of two lists creates all possible ordered pairs by combining each element from the first list with every element from the second list. Python provides multiple approaches to find the Cartesian product using itertools.product(), nested loops, or list comprehensions.
Problem Understanding
If we have two lists like [a, b] and [c, d], the Cartesian product will be [(a, c), (a, d), (b, c), (b, d)]. For input lists l1 = [1, 5, 6] and l2 = [1, 2, 9], the output should be all combinations of elements from both lists.
Using itertools.product()
The most efficient approach uses the built-in itertools.product() function ?
from itertools import product
def find_cartesian_product(l1, l2):
return list(product(l1, l2))
l1 = [1, 5, 6]
l2 = [1, 2, 9]
result = find_cartesian_product(l1, l2)
print(result)
[(1, 1), (1, 2), (1, 9), (5, 1), (5, 2), (5, 9), (6, 1), (6, 2), (6, 9)]
Using Nested Loops
A manual approach using nested loops for better understanding ?
def cartesian_with_loops(l1, l2):
result = []
for item1 in l1:
for item2 in l2:
result.append((item1, item2))
return result
l1 = [1, 5, 6]
l2 = [1, 2, 9]
result = cartesian_with_loops(l1, l2)
print(result)
[(1, 1), (1, 2), (1, 9), (5, 1), (5, 2), (5, 9), (6, 1), (6, 2), (6, 9)]
Using List Comprehension
A concise one-liner using list comprehension ?
def cartesian_comprehension(l1, l2):
return [(x, y) for x in l1 for y in l2]
l1 = [1, 5, 6]
l2 = [1, 2, 9]
result = cartesian_comprehension(l1, l2)
print(result)
[(1, 1), (1, 2), (1, 9), (5, 1), (5, 2), (5, 9), (6, 1), (6, 2), (6, 9)]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
itertools.product() |
High | Fastest | Production code |
| Nested loops | Medium | Slower | Learning/debugging |
| List comprehension | High | Good | Pythonic style |
Conclusion
Use itertools.product() for the most efficient Cartesian product calculation. List comprehensions offer a readable alternative, while nested loops help understand the underlying logic.
