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,572
  • 5
  • 26
  • 41

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,200
  • 2
  • 30
  • 44
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,080
  • 4
  • 38
  • 57
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
  • 2,984
  • 23
  • 42
1

One liner:

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

Freek Wiekmeijer
  • 3,976
  • 26
  • 34
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
  • 32,670
  • 6
  • 50
  • 72