Cartesian product of two lists in python

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.

Tags:

Python