-2

If I have
x = [1,2,3,4,5]
y = [6,7,8,9,10]

how can I get a two dimensional array in the form of
combined = [[1,6],[2,7],[3,8],[4,9],[5,10]]

Daniel Murphy
  • 330
  • 1
  • 2
  • 7
  • 3
    this is called `zip` – Farzher Mar 18 '18 at 21:30
  • 2
    Calling `zip` gives you an iterator over tuples, like `(1, 6)` instead of `[1, 6]`. If you're just looping over everything, that's just as good as a list of lists, but smaller and faster. If you actually need a list of lists, you need to call `list` on each one—e.g., `[list(pair) for pair in zip(x, y)]`. – abarnert Mar 18 '18 at 21:32

2 Answers2

0

A few options. Numpy should be your go-to tool for performant array operations. Sticking with your original input values:

np.array([x,y]).T.tolist()

With vanilla python, a list comprehension will do:

[[j,k] for j,k in zip(x,y)]

Or if you don't mind tuples in place of inner lists, you can use the more terse:

list(zip(x,y))

anon01
  • 10,618
  • 8
  • 35
  • 58
-2

Try numpy if you want:

import numpy as np

x = [1,2,3,4,5]
y = [6,7,8,9,10]

print(np.reshape(np.dstack((x,y)),[-1,2]))

output:

[[ 1  6]
 [ 2  7]
 [ 3  8]
 [ 4  9]
 [ 5 10]]
Aaditya Ura
  • 12,007
  • 7
  • 50
  • 88