numpy.shape() Function

The numpy.shape() function will return the shape of the given array in tuple format. 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.

Syntax

The Syntax of numpy.shape() method is:

numpy.shape(arr)

Parameters

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

  • arr (array_like) – The input array for fetching the 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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