Skip to content
Advertisement

Cartesian product of two lists in python [duplicate]

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

Advertisement

Answer

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]
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement