Skip to main content

12.3) Create an Array From A List


If your data is in a list, here’s how to convert it to an array:

>>> import numpy as np
>>> a=np.array([1,2,3,4,5,6])  # a 1D array (i.e. a vector)
>>> a
array([1, 2, 3, 4, 5, 6])
>>> print a
[1 2 3 4 5 6]
>>> type(a)
<type 'numpy.ndarray'>
>>> print np.array([[1,2,3],[4,5,6]]) # a 2D array
[[1 2 3]
 [4 5 6]]

Notice how the printing of the array is slightly different to a list: no commas and a neat printing for 2D arrays.

A frequent mistake is to call the function array with multiple numeric arguments, rather than providing a single list of numbers as an argument. Remember that the array() function transforms a sequence into an array.

>>> a = np.array(1,2,3,4) # is WRONG
>>> a = np.array([1,2,3,4]) # is CORRECT

Create a array with 2 rows and 3 columns from a list.