I have two lists.
A = [1,5,10]
B = [72,36,58]
I'd like to concatenate two lists based on the same index.
Output = [1,72,5,36,10,58]
I know I can use zip(A,B) to do so but in this way I need to remove tuple from the list.
Any hint or elegant way to do this?
You can use a nested list comprehension :
>>> [i for tup in zip(A,B) for i in tup]
[1, 72, 5, 36, 10, 58]
If you are dealing with huge datasets, using Numpy extension is a good choice for you, which in that case you would be able to use a lot of cool features. And in this case you can use numpy.hstack() to flatten the zip() result :
>>> import numpy as np
>>>
>>> np.hstack(zip(A,B))
array([ 1, 72, 5, 36, 10, 58])
Here's an itertools approach:
>>> from itertools import chain
>>> list(chain.from_iterable(zip(A, B)))
[1, 72, 5, 36, 10, 58]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With