2

Let's say I have:

a = [10,14,16]

b = [0,1,2]

and I want combine a and b into one list, as shown below:

print c
[[10, 0], [14, 1], [16, 2]]

I have tried to merge the two lists:

a + b
[10, 14, 16, 0, 1, 2]

but it's not same as what I want to achieve. How can I do that in Python?

CubeJockey
  • 2,209
  • 8
  • 24
  • 31
ihsansat
  • 503
  • 2
  • 7
  • 20
  • Possible duplicate of [How to append list to second list (concatenate lists)](http://stackoverflow.com/questions/1720421/how-to-append-list-to-second-list-concatenate-lists) – Rick Apr 18 '16 at 13:38

6 Answers6

6

This is what zip() is for:

>>> a = [10,14,16]
>>> b = [0,1,2]
>>> zip(a, b)
[(10, 0), (14, 1), (16, 2)]

Note that this would get you a list of tuples. In case you want a list of lists:

>>> [list(item) for item in zip(a, b)]
[[10, 0], [14, 1], [16, 2]]
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
4

You could use zip built in function. It's very efficient compared to manual implementation.

In [52]: c = list(zip(a,b))

In [53]: c
Out[53]: [(10, 0), (14, 1), (16, 2)]
C Panda
  • 3,297
  • 2
  • 11
  • 11
2
a = [10,14,16]
b = [0,1,2] 
c = []
for i in range(len(a)):
    c.append([a[i], b[i]])
print c

Or in one line:

print [[a[i], b[i]] for i in range(len(a))]

Outputs:

[[10, 0], [14, 1], [16, 2]]
Avión
  • 7,963
  • 11
  • 64
  • 105
0

using a simple for loop?

a = [10,14,16]
b = [0,1,2]
c = []
for i in range(len(a)):
    try:
        c.append([a[i],b[i]])
    except KeyError:
        c.append([a[i]])
print c

or by using a generator:

c = [ [a[i],b[i]] for i in range(len(a))]
János Farkas
  • 453
  • 5
  • 14
0
import numpy as np
np.array(a+b).reshape(2,3).T.tolist()
PhilChang
  • 2,591
  • 1
  • 16
  • 18
0

for small lists you can do a "for" loop:

a = [10,14,16]
b = [0,1,2]
for i in range(len(a)):
    out[i] = [a[i],b[i]]

Or for longer list you can use pandas to create a dataframe:

import pandas as pd
df = pd.dataframe([a,b],columns = ['a','b'])
out = df.T.values.tolist()
ysearka
  • 3,805
  • 5
  • 20
  • 41