Python Program to Get Numpy Array Shape or Dimensions

Numpy Array Shape

To get the shape or dimensions of a Numpy Array, use ndarray.shape where ndarray is the name of the numpy array you are interested of. ndarray.shape returns a tuple with dimensions along all the axis of the numpy array.

Example 1: Get Shape of Multi-Dimensional Numpy Array

In the following example, we have initialized a multi-dimensional numpy array. Of course, we know the shape of the array by its definition. But, we will use ndarray.shape property to get the shape of the array programmatically.

Python Program

import numpy as np

#initialize an array
arr = np.array([[[11, 11, 9, 9],
                  [11, 0, 2, 0]
				 ],
	             [[10, 14, 9, 14],
                  [0, 1, 11, 11]]])
# get array shape
shape = arr.shape
print(shape)
Run

Output

(2, 2, 4)

Example 2: Get Shape of 2D Numpy Array

In the following example, we will create a 2D numpy array and find its shape. There are two rows and four columns. So, we should get a tuple of (2, 4). Let us see.

Python Program

import numpy as np

#initialize an array
arr = np.array([[11, 11, 9, 9],
                  [11, 0, 2, 0]])
# get array shape
shape = arr.shape
print(shape)
Run

Output

(2, 4)

Example 3: Get Shape of 1-Dimensional Numpy Array

In the following example, we will find the shape of a one-dimensional numpy array.

Python Program

import numpy as np

#initialize an array
arr = np.array([11, 11, 9, 9])
# get array shape
shape = arr.shape
print(shape)
Run

There are four elements, and of course, the shape should be a tuple with 4.

Output

(4,)

Summary

In this Numpy Tutorial of Python Examples, we learned how to get the shape of a given numpy array as a tuple.