Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Combine Lists -- Retain Relative Ordering

Tags:

python

list

Not sure how to get this guy done...

have:

L1 = [1,2,3]
L2 = [a,b,c]

want:

[1,a,2,b,3,c]
like image 244
thenickname Avatar asked Oct 30 '25 01:10

thenickname


2 Answers

import itertools

L1 = [1,2,3]
L2 = ['a','b','c']
list(itertools.chain.from_iterable(itertools.izip(L1, L2)))

You could use izip_longest with a fill value for lists of uneven length.

like image 82
Imran Avatar answered Oct 31 '25 17:10

Imran


Zip the lists then flatten the result:

Z = zip(L1, L2)
print [x for item in Z for x in item]
like image 32
Jochen Ritzel Avatar answered Oct 31 '25 16:10

Jochen Ritzel



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!