numpy.ndarray.shape in Python

Numpy array has a shape attribute that tells you the number of elements along each dimension. It always returns the value in the form of a tuple.

Value of shape attribute for 1-Dimensional Numpy array

import numpy as np

a = np.array([2, 4, 6, 8, 10, 12, 14])
print(a.shape)

Output of the above program

(7, )

Here 7 means there are 7 elements in 1-dimensional array.

Value of shape attribute for 2-Dimensional Numpy array

import numpy as np

a = np.array([1, 2, 3, 4], [5, 6, 7, 8])
print(a.shape)

Output of the above program

(2, 4)

Here (2, 4) means that there are 2 rows and 4 columns in this array.

Note: Don't confuse yourself by looking at the shape attribute value for 1-D and 2-D Numpy array.

Value of shape attribute for 3-Dimensional Numpy array

import numpy as np

a = np.array([[[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]]])
print(a.shape)

Output of the above program

(2, 2, 4)

Here, (2, 2, 4) means that there two 2-Dimensional array. And each 2-dimensional array has 2 rows and 4 columns.

Recommended Posts