2

For list of strings, define the multiplication operation in as concatenating here:

l1 = ['aa', 'bb', 'cc']
l2 = ['11', '22']
l3 = l1 op l2

Expected output:

l3 = ['aa11', 'aa22', 'bb11', 'bb22', 'cc11', 'cc22']

Simply we can use

for l in l1:
    for ll in l2:
        l3.append(l+ll)

But I'd be grateful to hear a pythonic solution.

Georgy
  • 12,464
  • 7
  • 65
  • 73
CH_skar
  • 103
  • 5
  • 2
    What is "not pythonic" here? Do you mean "code that is hardly to understand = pythonic"? Think of developers who will support your code. They will be glad to have this logic exactly in such form (nested loops) as your have done. The solution of @jedwards is also good from the point of view of maintainability and understanding. – mentallurg Jun 04 '18 at 22:42
  • What you implemented *is not* a dot product. – Olivier Melançon Jun 05 '18 at 00:03
  • @OlivierMelançon Correct. It should be phrased as multilication. – CH_skar Jun 05 '18 at 02:07
  • 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
  • is op the + operation or is op a function – Golden Lion Jun 01 '21 at 15:56

2 Answers2

4
from itertools import product

l1 = ['aa', 'bb', 'cc']
l2 = ['11', '22']

l3 = [x+y for (x,y) in product(l1,l2)]

print(l3)

But it's effectively the same thing as what you're doing (provided you fix the typo :P)

jedwards
  • 29,432
  • 3
  • 65
  • 92
2
l3 = [a+b for a in l1 for b in l2]
iacob
  • 20,084
  • 6
  • 92
  • 119