1

Looking to combine two list variables containing string elements. For example, if I have the below :

mystring1 = ['Luke', 'Han']
mystring2 = ['Skywalker', 'Solo']

I am looking to combine them to be :

mystring3 = ['LukeSkywalker', 'HanSolo']

I am sure I am missing something simple. Any guidance would be great!

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
JDV_ny
  • 11
  • 1
  • 2

5 Answers5

9

Simply map the two lists to str.__add__:

list(map(str.__add__, mystring1, mystring2))

This outputs:

['LukeSkywalker', 'HanSolo']

As a side note, if you want to combine more than two lists of strings at a time, you can do:

mystring1 = ['Luke', 'Han']
mystring2 = ['Skywalker', 'Solo']
mystring3 = ['Hero', 'Sidekick']
from functools import partial, reduce
print(list(reduce(partial(map, str.__add__), (mystring1, mystring2, mystring3))))

This outputs:

['LukeSkywalkerHero', 'HanSoloSidekick']
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Great I never knew `map` took multiple iterables. You could remove the need for using the dunder method if you used [`operator.add`](https://docs.python.org/3.7/library/operator.html#operator.add) – Paul Rooney Jul 18 '18 at 03:36
  • thank you!!! this is great. – JDV_ny Jul 18 '18 at 10:16
  • @JDV_ny Glad to be of help. Can you mark this answer as accepted if you think it is correct? – blhsing Jul 18 '18 at 10:58
5

The following should work:

>>> mystring1 = ['Luke', 'Han']
>>> mystring2 = ['Skywalker', 'Solo']
>>> list(map(''.join, zip(mystring1, mystring2)))
['LukeSkywalker', 'HanSolo']
>>> 
Pankaj Singhal
  • 15,283
  • 9
  • 47
  • 86
4

Just use zip and then concatenate the strings.

This obviously only works if there are exactly two strings you wish to join. If there were more, then use str.join like some of the other answers suggest. With 2 strings however the concat method is more readable.

>>> mystring1 = ['Luke', 'Han']
>>> mystring2 = ['Skywalker', 'Solo']
>>> 
>>> [s1 + s2 for s1, s2 in zip(mystring1, mystring2)]
['LukeSkywalker', 'HanSolo']

zip simply takes one element from each of the iterables passed to it, on each iteration and returns a tuple of those elements. The intermediate result of the zip operation looks like

[('Luke', 'Skywalker'), ('Han', 'Solo')]
Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
1
map(lambda x: x[0] + x[1], zip(mystring1, mystring2))

Zipping the two produces an iterable (or list, if you're in Python 2) of 2-tuples. Then map over the iterable (resp. list) to convert to the result you want.

Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
1
import pandas as pd
mystring1 = ['Luke', 'Han']
mystring2 = ['Skywalker', 'Solo']
df=pd.DataFrame([mystring1,mystring2]).T
df.columns=list('01')
print((df['0']+df['1']).tolist())

Output:

['LukeSkywalker', 'HanSolo']
U13-Forward
  • 69,221
  • 14
  • 89
  • 114