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
  • 66,333
  • 7
  • 57
  • 95
Dyno
  • 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,352
  • 6
  • 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
  • 23,210
  • 7
  • 49
  • 68
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
  • 7,382
  • 12
  • 27
  • 61
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
  • 23,210
  • 7
  • 49
  • 68
nassim
  • 1,399
  • 1
  • 11
  • 25
  • This is a more verbose version of [Mark Bailey's answer](https://stackoverflow.com/a/55858533/4518341) – wjandrea Apr 25 '19 at 22:51