How to concatenate two lists of strings in Python
I have two lists of string:
a = ['a', 'b', 'c']
b = ['d', 'e', 'f']
I have to quote:
['ad', 'be', 'cf']
What's the most pythonic way to do this?
Perhaps zip
:
c = [''.join(item) for item in zip(a,b)]
You can also put multiple subscriptions in one big iterable and use an 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 *
c operator zip
to jump in the other direction:
>>> list(zip(*c))
[('a', 'b', 'c'), ('d', 'e', 'f')]
you can use zip
>>> a = ['a', 'b', 'c']
>>> b = ['d', 'e', 'f']
>>> [ai+bi for ai,bi in zip(a,b)]
['ad', 'be', 'cf']
What about:
[c + d for c,d in zip(a,b)]
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 an enum combo:
[j+b[i] for i,j in enumerate(a)] ['ad', 'be', 'cf']
You can use lambda
together with map
:
map(lambda x,y:x+y,a,b)
Or add zip
to manage more than two lists:
map(lambda x:''.join(x), zip(a,b,c))
For python <3 I would prefer the former option or replace zip()
with izip()
, for python 3 this change is not required ( zip
already returns an iterator).