2

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

bk_
  • 751
  • 1
  • 8
  • 27
  • You could use list comprehension but since the complexity is the same stick to a format that is easier for you to understand\debug – Tamir Nov 12 '20 at 09:42
  • 2
    `product()` from the itertools package gives you a list of tuples with one element each from either list. You'll still need to iterate over that list to concatenate the tuple components. There's no better way of doing this than a list comprehension. – Björn Marschollek Nov 12 '20 at 09:45

4 Answers4

5

You could use list comprehension:

print([f"{a}{b}" for a in l1 for b in l2])
alex_noname
  • 26,459
  • 5
  • 69
  • 86
4

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']
Maciej M
  • 786
  • 6
  • 17
2

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']
Björn Marschollek
  • 9,899
  • 9
  • 40
  • 66
0

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']
Wasif
  • 14,755
  • 3
  • 14
  • 34