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']
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']
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']
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.
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)