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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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]

Method 2

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.

Method 3

You could use itertools.product function:

from itertools import product

list3 = [a+str(b) for a, b in product(list1, list2)]

Method 4

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x