Sometimes, we want to get the cartesian product of a series of lists with Python.
In this article, we’ll look at how to get the cartesian product of a series of lists with Python.
How to get the cartesian product of a series of lists with Python?
To get the cartesian product of a series of lists with Python, we can use the itertools.product
method.
For instance, we write:
import itertools
some_lists = [
[1, 2, 3],
['a', 'b'],
[4, 5]
]
for element in itertools.product(*some_lists):
print(element)
We call itertools.product
with the lists in some_lists
spread into it as arguments.
Then we print all the tuples that are in the cartesian products list.
Therefore, we get:
(1, 'a', 4)
(1, 'a', 5)
(1, 'b', 4)
(1, 'b', 5)
(2, 'a', 4)
(2, 'a', 5)
(2, 'b', 4)
(2, 'b', 5)
(3, 'a', 4)
(3, 'a', 5)
(3, 'b', 4)
(3, 'b', 5)
printed.
Conclusion
To get the cartesian product of a series of lists with Python, we can use the itertools.product
method.