Most Pythonic way to form cartesian product of two lists of strings

Question:

I have two lists of strings:

l1 = ["Col1", "Col2", "Col3"]
l2 = ["_ad1", "_ad2"]

and I want to get the cartesian product / Concatenation of both lists l1 x l2 into a single element, i.e. my desired result is:

["Col1_ad1", "Col1_ad2", "Col2_ad1", "Col2_ad2", "Col3_ad1", "Col1_ad1"]

Of course I could to something like:

result = []
for colname in l1:
    for suffix in l2:
        result.append(f"{colname}{suffix}")

But I was wondering whether there is a more pythonic way?

EDIT: I am not looking for a more pythonic way to formulate the loop (i.e. list comprehension). Instead I am looking for an inbuilt function, something like
concatenate(l1, l2) that yields the desired result

Asked By: bk_

||

Answers:

You could use list comprehension:

print([f"{a}{b}" for a in l1 for b in l2])
Answered By: alex_noname

You could try a list comprehension:

>>> l1 = ["Col1", "Col2", "Col3"]
>>> l2 = ["_ad1", "_ad2"]
>>> [f"{a}{b}" for a in l1 for b in l2]
['Col1_ad1', 'Col1_ad2', 'Col2_ad1', 'Col2_ad2', 'Col3_ad1', 'Col3_ad2']
Answered By: Björn Marschollek

Try out a list comprehension:

print([x+y for x in l1 for y in l2])

You can use format strings too:

print(["{}{}".format(x,y) for x in l1 for y in l2])

For python 3.6+ only (Pointed by @AlexNomane):

print([f"{x}{y}" for x in l1 for y in l2])

All output:

['Col1_ad1', 'Col1_ad2', 'Col2_ad1', 'Col2_ad2', 'Col3_ad1', 'Col3_ad2']
Answered By: Wasif

You can do this using itertools.product

>>> from itertools import product
>>> l1 = ["Col1", "Col2", "Col3"]
>>> l2 = ["_ad1", "_ad2"]
>>> list(elem[0] + elem[1] for elem in product(l1, l2))
['Col1_ad1', 'Col1_ad2', 'Col2_ad1', 'Col2_ad2', 'Col3_ad1', 'Col3_ad2']
Answered By: Maciej M