Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate two list based on the same index

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?

like image 218
Sakura Avatar asked Nov 22 '25 06:11

Sakura


2 Answers

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])
like image 75
Mazdak Avatar answered Nov 23 '25 19:11

Mazdak


Here's an itertools approach:

>>> from itertools import chain
>>> list(chain.from_iterable(zip(A, B)))
[1, 72, 5, 36, 10, 58]
like image 39
tzaman Avatar answered Nov 23 '25 20:11

tzaman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!