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']
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.
You could use itertools.product function:
from itertools import product
list3 = [a+str(b) for a, b in product(list1, list2)]