NumPy Shape

The NumPy array library has a built-in method numpy.shape()that will return the shape of the array. The shape of the array is the elements in each dimension. Dimension is the count of indices that are required to access or refer to an individual element of the array.

For example, if the array has the shape (2, 4) means that the array has 2 dimensions and for each dimension, there are 4 elements.

NumPy Shape Syntax

The Syntax of numpy.shape() method is:

numpy.shape(arr)

NumPy Shape Parameters

The numpy.shape() accepts single argument as shown below

  • arr (array_like) – The input array for fetching the shape

NumPy Shape Return Value

The return value of the shape is a tuple that gives the length of corresponding array dimensions.

Example 1: Fetching the shape of a NumPy array

# import numpy to be used as np
import numpy as np

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

# print numpy  array
print("The input array is:\n\n", array_in)

# shape of the array
print("\nThe shape of the array is:\n\n", np.shape(array_in))

Output

The input array is:

 [[ 1  2  3  4]
 [ 5  6  7  8] 
 [ 9 10 11 12]]

The shape of the array is:

 (3, 4)

Example 2: Creating an array using ndmin and verifying the last dimension

import numpy as np

# ndim attribute is used to return an integer to fetch the dimension of the array
array_in = np.array([1, 2, 3, 4], ndmin=5)

# print array
print("The input array is:\n", array_in)

# shape of the array
print("\nshape of array is :\n", np.shape(array_in))

Output

The input array is:

 [[[[[1 2 3 4]]]]]

shape of array is :

 (1, 1, 1, 1, 4)

Note: ndim() attribute will return an integer that will contain the dimension of the array to be created.

Conclusion

NumPy array library has an inbuilt method, numpy.shape() that will return the shape of the array in a tuple format that gives the length of corresponding array dimensions.

Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Python Complex()

Python complex()

Table of Contents Hide complex() Syntax complex() Parameterscomplex() Return ValueExample 1: How to create a complex number in Python?Example 2: TypeError while converting string with imaginary parameterExample 3: ValueError if string…
View Post