Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Creation of Numpy arrays

Code using numpy usually starts with the import statement

import numpy as np

NumPy provides the type np.ndarray. Such array are multidimensionnal sequences of homogeneous elements. They can be created for example with the commands:

# from a list
l = [10.0, 12.5, 15.0, 17.5, 20.0]
np.array(l)
array([10. , 12.5, 15. , 17.5, 20. ])
# fast but the values can be anything
np.empty(4)
array([4.64978657e-310, 0.00000000e+000, 4.65078706e-310, 4.65078738e-310])
# slower than np.empty but the values are all 0.
np.zeros([2, 6])
array([[0., 0., 0., 0., 0., 0.], [0., 0., 0., 0., 0., 0.]])
# multidimensional array
a = np.ones([2, 3, 4])
print(a.shape, a.size, a.dtype)
a
(2, 3, 4) 24 float64
array([[[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]], [[1., 1., 1., 1.], [1., 1., 1., 1.], [1., 1., 1., 1.]]])
# like range but produce 1D numpy array
np.arange(4)
array([0, 1, 2, 3])
# np.arange can produce arrays of floats
np.arange(4.0)
array([0., 1., 2., 3.])
# another convenient function to generate 1D arrays
np.linspace(10, 20, 5)
array([10. , 12.5, 15. , 17.5, 20. ])

A NumPy array can be easily converted to a Python list.

a = np.linspace(10, 20, 5)
list(a)
[np.float64(10.0), np.float64(12.5), np.float64(15.0), np.float64(17.5), np.float64(20.0)]
# Or even better
a.tolist()
[10.0, 12.5, 15.0, 17.5, 20.0]