0

I have not found an answer to my question: (maybe not the words to found it) I have two lists, I would like to add each element (and keep the order) to another list. For example:

A = ["abc", "def", "ghi"]
B = ["123", "456", "789"]

result = ["abc123", "def456", "ghi789"]

Thanks

Guillaume
  • 2,752
  • 5
  • 27
  • 42

5 Answers5

2
result=[]
for i,j in zip(A,B):
        result.append(i+j)

also:
map(lambda x : x[0]+x[1],zip(A,B))

list comprehension we can acheive it in single line

[ x+y for x,y in zip(A,B)]

explanation: above code is a list in which elements are x+y from the zip(A,B)

sundar nataraj
  • 8,524
  • 2
  • 34
  • 46
2
result = [ a + b for a, b in zip(A, B) ]

Even better (using a generator instead of an intermediate list):

from itertools import izip
result = [ a + b for a, b in izip(A,B) ]
Oleg Sklyar
  • 9,834
  • 6
  • 39
  • 62
1
result = [ str(a)+str(b) for a, b in zip(A, B) ]

Thanks to str() usage, you can have lists of any objects, not only strings, and your result will be list of strings.

Filip Malczak
  • 3,124
  • 24
  • 44
1

One liner:

map (lambda t: t[0]+t[1], zip(A,B))

Freek Wiekmeijer
  • 4,556
  • 30
  • 37
1

An alternative way would be using operator.__add__ and map().

from operator import __add__

A = ["abc", "def", "ghi"]
B = ["123", "456", "789"]

print map(__add__, A, B)
Christian Tapia
  • 33,620
  • 7
  • 56
  • 73
  • why adding a module? I have already so much in my program – Guillaume Jun 03 '14 at 07:40
  • `from operator import __add__` will only import the built-in function `__add__`, not the whole module. Also, this approach [has the advantage that is faster than others](http://stackoverflow.com/a/18713344/2670792), except for a numPy solution. – Christian Tapia Jun 03 '14 at 07:42