how to convert 2d list to 2d numpy array?


I have a 2D list something like

a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] 

and I want to convert it to a 2d numpy array. Can we do it without allocating memory like


and then storing values to it?

This question is tagged with python numpy

~ Asked on 2011-10-10 19:03:32

The Best Answer is


Just pass the list to np.array:

a = np.array(a)

You can also take this opportunity to set the dtype if the default is not what you desire.

a = np.array(a, dtype=...)

~ Answered on 2011-10-10 19:07:36


np.array() is even more powerful than what unutbu said above. You also could use it to convert a list of np arrays to a higher dimention array, the following is a simple example:



aList=[aArray, bArray]


xArray's shape is (2,3), it's a standard np array. This operation avoids a loop programming.

~ Answered on 2017-11-02 09:33:38

Most Viewed Questions: