Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Intertwining two lists

What is the pythonic way of doing the following:

I have two lists a and b of the same length n, and I want to form the list

c = [a[0], b[0], a[1], b[1], ..., a[n-1], b[n-1]]
like image 904
Johan Råde Avatar asked Jun 15 '11 10:06

Johan Råde


3 Answers

c = [item for pair in zip(a, b) for item in pair]

Read documentation about zip.


For comparison with Ignacio's answer see this question: How do I convert a tuple of tuples to a one-dimensional list using list comprehension?

like image 118
orlp Avatar answered Oct 02 '22 13:10

orlp


c = list(itertools.chain.from_iterable(itertools.izip(a, b)))
like image 20
Ignacio Vazquez-Abrams Avatar answered Oct 02 '22 13:10

Ignacio Vazquez-Abrams


c = [item for t in zip(a,b) for item in t]
like image 39
manji Avatar answered Oct 02 '22 13:10

manji