Combining two lists side by side

I am looking for the shortest way to do the following (one line solution)

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

      

I need the following output:

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

      

Of course, this can be achieved using a for loop. But I'm wondering if there is a sane solution?

+3


source to share


5 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']

      

+8


source


You can use zip

in a list comprehension:



>>> ['{} {}'.format(*i) for i in zip(a,b)]
['a w', 'b e', 'c r']

      

+5


source


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

print(["{} {}".format(_a ,_b) for _a,_b in zip(a,b)])
['a w', 'b e', 'c r']

      

+1


source


one line solution:

[aa+" "+bb for aa,bb in zip(a,b)]

      

output:

['a w', 'b e', 'c r']

      

one liner without zip:

[a[i]+" "+b[i] for i in range(len(a))]

      

output:

['a w', 'b e', 'c r']

      

+1


source


More pythonic way;

b = map(' '.join,zip(a,b))

      

+1


source







All Articles