NumPy Array Shape

Array Shape

The shape of the array is the number of elements in each dimension.

Get the shape of the array

NumPy arrays have a named shape The attribute, which returns a tuple with the number of elements at each index.

Example

Print the shape of a 2-D array:

import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape)

Run Instance

The above example returns (2, 4), which means that the array has 2 dimensions, each with 4 elements.

Example

Using ndmin Create an array with 5 dimensions using the vector with values 1, 2, 3, 4, and verify that the value of the last dimension is 4:

import numpy as np
arr = np.array([1, 2, 3, 4], ndmin=5)
print(arr)
print('shape of array:', arr.shape)

Run Instance

What does the shape of the tuple represent?

The integer at each index indicates the number of elements in the corresponding dimension.

The index 4 in the above example, our value is 4, so we can say that the 5th (4 + 1st) dimension has 4 elements.