Reputation: 134
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
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
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
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