13

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']
Sociopath
  • 12,395
  • 17
  • 43
  • 69
mohsen h
  • 157
  • 1
  • 1
  • 7
  • 1
    Does this answer your question? [concatenate strings in 2 different lists in python](https://stackoverflow.com/questions/36885876/concatenate-strings-in-2-different-lists-in-python) – Georgy May 09 '20 at 14:47

4 Answers4

13

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]
Raunaq Jain
  • 887
  • 7
  • 13
9

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.

lmiguelvargasf
  • 51,786
  • 40
  • 198
  • 203
5

You could use itertools.product function:

from itertools import product

list3 = [a+str(b) for a, b in product(list1, list2)]
miindlek
  • 3,485
  • 13
  • 25
1

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

Brent
  • 650
  • 1
  • 5
  • 9