Cartesian product of two lists in python

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']

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]

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)]

if you're not familiar with list comprehension you could also use

list3 = []
for l in list1:
    for b in list2:
        list3.append(l + b)
print list3

this will do the same exact thing, but using the list comprehension from above would be the best way