5.2.3. Creating arrays from lists#
A simple way to create an array from a list is to use the np.array function. To create the unidimensional array of Fig. 5.2, we would write:
import numpy as np
array_1d = np.array([0.0, 0.1, 0.2, 0.3])
array_1d
array([0. , 0.1, 0.2, 0.3])
It is also possible to convert back an array to a list, using its tolist method:
array_1d.tolist()
[0.0, 0.1, 0.2, 0.3]
To create the bidimensional array of Fig. 5.3, we would use nested lists:
array_2d = np.array(
[
[0.0, 0.1, 0.2, 0.3],
[0.4, 0.5, 0.6, 0.7],
[0.8, 0.9, 1.0, 1.1],
]
)
array_2d
array([[0. , 0.1, 0.2, 0.3],
[0.4, 0.5, 0.6, 0.7],
[0.8, 0.9, 1. , 1.1]])
To create the tridimensional array of Fig. 5.4, we would use multiple levels of nested lists:
array_3d = np.array(
[
[
[0.0, 0.1, 0.2, 0.3],
[0.4, 0.5, 0.6, 0.7],
[0.8, 0.9, 1.0, 1.1],
],
[
[1.2, 1.3, 1.4, 1.5],
[1.6, 1.7, 1.8, 1.9],
[2.0, 2.1, 2.2, 2.3],
],
[
[2.4, 2.5, 2.6, 2.7],
[2.8, 2.9, 3.0, 3.1],
[3.2, 3.3, 3.4, 3.5],
],
]
)
array_3d
array([[[0. , 0.1, 0.2, 0.3],
[0.4, 0.5, 0.6, 0.7],
[0.8, 0.9, 1. , 1.1]],
[[1.2, 1.3, 1.4, 1.5],
[1.6, 1.7, 1.8, 1.9],
[2. , 2.1, 2.2, 2.3]],
[[2.4, 2.5, 2.6, 2.7],
[2.8, 2.9, 3. , 3.1],
[3.2, 3.3, 3.4, 3.5]]])