Cartesian product of two lists in python
list1 = ['a', 'b']
list2 = [1, 2, 3, 4, 5]
Expected Output:
list3 = ['a1', 'a2', 'a3', 'a4', 'a5', 'b1', 'b2', 'b3', 'b4', 'b5']
Get Cartesian Product in Python Using the itertools ModuleThe product(*iterables, repeat=1) method of the itertools module takes iterables as input and returns their cartesian product as output. The cartesian product order will be the order of each set/list in the provided argument iterables .
The Cartesian square of a set X is the Cartesian product X2 = X × X. An example is the 2-dimensional plane R2 = R × R where R is the set of real numbers: R2 is the set of all points (x,y) where x and y are real numbers (see the Cartesian coordinate system).
In mathematics, the Cartesian Product of sets A and B is defined as the set of all ordered pairs (x, y) such that x belongs to A and y belongs to B. For example, if A = {1, 2} and B = {3, 4, 5}, then the Cartesian Product of A and B is {(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)}.
If you are using Python 3.6+ you can use f-strings as follows:
list3 = [f'{a}{b}' for a in list1 for b in list2]
I really like this notation because it is very readable and matches with the definition of the cartesian product.
If you want more sophisticated code, you could use itertools.product
:
import itertools
list3 = [f'{a}{b}' for a, b in itertools.product(list1, list2)]
I checked the performance, and it seems the list comprehension runs faster than the itertools
version.
Do a list comprehension, iterate over both the lists and add the strings, like
list3 = [i+str(j) for i in list1 for j in list2]
You could use itertools.product function:
from itertools import product
list3 = [a+str(b) for a, b in product(list1, list2)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With