17

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]]
Ryan Haining
  • 35,360
  • 15
  • 114
  • 174
Johan Råde
  • 20,480
  • 21
  • 73
  • 110

6 Answers6

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

Community
  • 1
  • 1
orlp
  • 112,504
  • 36
  • 218
  • 315
10
c = list(itertools.chain.from_iterable(itertools.izip(a, b)))
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
7
c = [item for t in zip(a,b) for item in t]
manji
  • 47,442
  • 5
  • 96
  • 103
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

Rusty Rob
  • 16,489
  • 8
  • 100
  • 116
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].)

Johan Råde
  • 20,480
  • 21
  • 73
  • 110
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()
btel
  • 5,563
  • 6
  • 37
  • 47