Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate two lists side by side

Tags:

python

list

I am looking for the shortest way of doing the following (one line solution)

a = ["a", "b", "c"]
b = ["w", "e", "r"]

I want the following output:

q = ["a w", "b e", "c r"]

Of course this can be achieved by applying a for loop. But I am wondering if there is a smart solution to this?

like image 724
user3664020 Avatar asked Aug 10 '15 09:08

user3664020


3 Answers

You can use str.join() and zip() , Example -

q = [' '.join(x) for x in zip(a,b)]

Example/Demo -

>>> a = ["a", "b", "c"]
>>> b = ["w", "e", "r"]
>>> q = [' '.join(x) for x in zip(a,b)]
>>> q
['a w', 'b e', 'c r']
like image 128
Anand S Kumar Avatar answered Nov 18 '22 16:11

Anand S Kumar


You can use zip within a list comprehension :

>>> ['{} {}'.format(*i) for i in zip(a,b)]
['a w', 'b e', 'c r']
like image 33
Mazdak Avatar answered Nov 18 '22 16:11

Mazdak


More pythonic way;

b = map(' '.join,zip(a,b))
like image 2
Alexey Astahov Avatar answered Nov 18 '22 16:11

Alexey Astahov