Reputation: 974
I have three lists
a = ['abc', 'def', 'ghi']
b = ['123', '456', '789']
c = ['mar23', 'feb223', 'jan12']
How can I make this as follows:
d = ['abc 123 mar23', 'def 456 feb223', 'ghi 789 jan12']
presently I am doing a for loop and doing index based concatenation. There should be an elegant way. Especially the space between them is causing the challenge. I am not looking for a dictionary.
Upvotes: 1
Views: 116
Reputation: 5459
You can also use list comprehension:
d = [f'{a[i]} {b[i]} {c[i]}' for i,x in enumerate(a)]
Output:
['abc 123 mar23', 'def 456 feb223', 'ghi 789 jan12']
As in the accepted answer it is claimed that zip
is faster than loop
, I have made an extensive evaluation of both of them. The results show that if for smaller lists loop
performs faster, but as the number of the elements increase zip
outperforms. Here some graphs:
1. Amount of indices in the interval [4,64]
:
2. Amount of indices in the interval [64,4194304]
:
Upvotes: 0
Reputation: 13888
Use zip
and list comprehension:
[' '.join(z) for z in zip(a, b, c)]
Result:
['abc 123 mar23', 'def 456 feb223', 'ghi 789 jan12']
Using index based vs zip
runtime (n=1000000
):
with index: 5.751067761
with zip: 4.115390091
Upvotes: 4
Reputation: 434
Use the Zip() function simply like this:
a = ['abc', 'def', 'ghi']
b = ['123', '456', '789']
c = ['mar23', 'feb223', 'jan12']
d = zip(a, b, c)
print(tuple(d))
Let me explain what is happening: We are first declaring 3 variables. Then, in order to join them together, we have a function zip() in Python which zips(or combines) the lists. So once we zip(a, b, c), we simply combine these 3 variables as a tuple while printing d(which contains the zipped items).
Hope it helps
Upvotes: 1
Reputation: 387
What you want is Python's zip
In [1]: a = ['abc', 'def', 'ghi']
...: b = ['123', '456', '789']
...: c = ['mar23', 'feb223', 'jan12']
In [2]: [' '.join(t) for t in zip(a, b, c)]
Out[2]: ['abc 123 mar23', 'def 456 feb223', 'ghi 789 jan12']
Upvotes: 1