18

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]]
0

6 Answers 6

27
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?

Sign up to request clarification or add additional context in comments.

Comments

10
c = list(itertools.chain.from_iterable(itertools.izip(a, b)))

Comments

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

Comments

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

Alternatively you could try:

c=[(a,b)[i%2][i/2] for i in xrange(2*n)]

which is of course less readable

Comments

1

Here is another way:

sum(([x,y] for (x,y) in zip(a,b)), [])

(Maybe not very efficient since you form both temporary tuples (x,y) and temporary lists [x,y].)

Comments

0

How about this one (tested on Python 2 and 3):

list(sum(zip(a, b), ()))

or in numpy:

import numpy as np
np.vstack((a, b)).T.flatten().tolist()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.