Curriculum
Course: NumPy
Login

Curriculum

NumPy

Text lesson

Check Number of Dimensions?

NumPy arrays offer the ndim attribute, which returns an integer indicating the number of dimensions in the array.

Example

Determine the number of dimensions of the arrays.

import numpy as np

a = np.array(42)
b = np.array([12345])
c = np.array([[123], [456]])
d = np.array([[[123], [456]], [[123], [456]]])

print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)

Higher Dimensional Arrays

An array can have any number of dimensions. When creating the array, you can specify the number of dimensions using the ndmin argument.

Example

Create an array with five dimensions and confirm that it indeed has five dimensions.

import numpy as np

arr = np.array([1234], ndmin=5)

print(arr)
print(‘number of dimensions :’, arr.ndim)