0

I'm trying to concatenate each character from 2 strings in a list. Also, is it possible to do it by using list comprehension?

s = ['ab', 'cde']

Result:

['ac', 'ad', 'ae', 'bc', 'bd', 'be']
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
mateo
  • 103
  • 1
  • 8
  • Related: [itertools product to generate all possible strings of size 3](https://stackoverflow.com/q/27413493/4518341) – wjandrea Apr 25 '19 at 22:54

4 Answers4

4

This will do it

result = [i + j for i in s[0] for j in s[1]]
Mark Bailey
  • 1,617
  • 1
  • 7
  • 13
3

This is probably a duplicate, but for completeness, here's your answer:

>>> import itertools
>>> s = ['ab', 'cde']
>>> [''.join(t) for t in itertools.product(*s)]
['ac', 'ad', 'ae', 'bc', 'bd', 'be']
wjandrea
  • 28,235
  • 9
  • 60
  • 81
1

Consider using itertools.product:

import itertools
s = ['ab', 'cde']
result = [''.join(item) for item in itertools.product(*s)]
print(result)  # ['ac', 'ad', 'ae', 'bc', 'bd', 'be']

There is no need to reimplement the wheel with list comprehensions.

sanyassh
  • 8,100
  • 13
  • 36
  • 70
0

please try this

s = ['ab', 'cde']

word1 = list(s[0])
word2 = list(s[1])

s2 = []

for c1 in word1:
  for c2 in word2:
      s2.append(c1+c2)

print(s2)
wjandrea
  • 28,235
  • 9
  • 60
  • 81
nassim
  • 1,547
  • 1
  • 14
  • 26
  • This is a more verbose version of [Mark Bailey's answer](https://stackoverflow.com/a/55858533/4518341) – wjandrea Apr 25 '19 at 22:51