Nicolargo
Nicolargo

Reputation: 134

How to merge two lists of string in Python

I have two lists of string:

a = ['a', 'b', 'c']
b = ['d', 'e', 'f']

I should result:

['ad', 'be', 'cf']

What is the most pythonic way to do this ?

Upvotes: 3

Views: 261

Answers (5)

dlavila
dlavila

Reputation: 1212

You can use lambda together with map:

map(lambda x,y:x+y,a,b)

Or add zip to manage more than 2 lists:

map(lambda x:''.join(x), zip(a,b,c))

For python < 3 I would prefer the former option or replace zip() for izip(), for python 3 the change is not necessary (zip already return an iterator).

Upvotes: 0

TigerhawkT3
TigerhawkT3

Reputation: 49318

Probably with zip:

c = [''.join(item) for item in zip(a,b)]

You can also put multiple sublists into one large iterable and use the * operator to unpack it, passing each sublist as a separate argument to zip:

big_list = (a,b)
c = [''.join(item) for item in zip(*biglist)]

You can even use the * operator with zip to go in the other direction:

>>> list(zip(*c))
[('a', 'b', 'c'), ('d', 'e', 'f')]

Upvotes: 7

Rahul Gupta
Rahul Gupta

Reputation: 47846

You can use zip:

zip(a,b)
[('a', 'd'), ('b', 'e'), ('c', 'f')]

[x+y for x,y in zip(a,b)]
['ad', 'be', 'cf']

You can also use enumerate with list comprehension:

[j+b[i] for i,j in enumerate(a)]
['ad', 'be', 'cf']

Upvotes: 0

cr1msonB1ade
cr1msonB1ade

Reputation: 1716

How about:

[c + d for c,d in zip(a,b)]

Upvotes: 1

khelwood
khelwood

Reputation: 59112

You can use zip

>>> a = ['a', 'b', 'c']
>>> b = ['d', 'e', 'f']

>>> [ai+bi for ai,bi in zip(a,b)]

['ad', 'be', 'cf']

Upvotes: 1

Related Questions