NumPy Array Shape

In Python Numpy, the number of elements in each dimension of an array is called the shape. To get the shape of a Numpy array, use the numpy.shape attribute in Python.

In this lesson, we have covered the following examples:

  • Check the shape of a Zero-Dimensional NumPy array
  • Check the shape of a One-Dimensional NumPy array
  • Check the shape of a Two-Dimensional NumPy array
  • Check the shape of a Three-Dimensional NumPy array

Check the shape of a Zero-Dimensional NumPy array

Let us see an example and create a Zero-Dimensional NumPy array to check the shape:

import numpy as np

n = np.array(10)

print(n)
print(n.dim)
print(n.shape)

Output

10
0
()

Check the shape of a One-Dimensional NumPy array

Let us see an example and create a One-Dimensional NumPy array to check the shape:

import numpy as np

n = np.array([10, 20, 30])

print(n)
print(n.ndim)
print(n.shape)

Output

[10 20 30]
1
(3,)

Checking the shape of a Two-Dimensional NumPy array

Let us see an example and create a Two-Dimensional NumPy array to check the shape:

import numpy as np

n = np.array([[1, 3, 5], [4, 8, 12]])

print(n)
print(n.ndim)
print(n.shape)

Output

[[ 1  3  5]
 [ 4  8 12]]
2
(2, 3)

Check the shape of a Three-Dimensional NumPy array

Let us see an example and create a Three-Dimensional NumPy array to check the shape:

import numpy as np

n = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

print(n)
print(n.ndim)
print(n.shape)

Output

[[[ 1  2  3]
  [ 4  5  6]]

 [[ 7  8  9]
  [10 11 12]]]
3
(2, 2, 3)

If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.

For Videos, Join Our YouTube Channel: Join Now


Read More:

Datatypes in Numpy
Reshape a Numpy array
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment