Open In App
Related Articles

NumPy Array Shape

Like Article
Save Article
Report issue

The shape of an array can be defined as the number of elements in each dimension. Dimension is the number of indices or subscripts, that we require in order to specify an individual element of an array.

How can we get the Shape of an Array?

In NumPy, we will use an attribute called shape which returns a tuple, the elements of the tuple give the lengths of the corresponding array dimensions.

Syntax: numpy.shape(array_name) 

Parameters: Array is passed as a Parameter. 

Return: A tuple whose elements give the lengths of the corresponding array dimensions.

Shape Manipulation in NumPy

Below are some examples by which we can understand about shape manipulation in NumPy in Python:

Example 1: Shape of Arrays

Printing the shape of the multidimensional array. In this example, two NumPy arrays arr1 and arr2 are created, representing a 2D array and a 3D array, respectively. The shape of each array is printed, revealing their dimensions and sizes along each dimension.


import numpy as npy
# creating a 2-d array
arr1 = npy.array([[1, 3, 5, 7], [2, 4, 6, 8]])
# creating a 3-d array
arr2 = npy.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])



(2, 4)
(2, 2,2)

Example 2: Shape of Array Using ndim

In this example, we are creating an array using ndmin using a vector with values 2,4,6,8,10 and verifying the value of last dimension.


import numpy as npy
# creating an array of 6 dimension
# using ndim
arr = npy.array([2, 4, 6, 8, 10], ndmin=6)
# printing array
# verifying the value of last dimension
# as 5
print('shape of an array :', arr.shape)



[[[[[[ 2  4  6  8 10]]]]]]
shape of an array : (1, 1, 1, 1, 1, 5)

Example 3: Shape of Array of Tuples

In this example, we’ll create a NumPy array where each element is a tuple. We’ll also demonstrate how to determine the shape of such an array.


import numpy as np
# Create an array of tuples
array_of_tuples = np.array([(1, 2), (3, 4), (5, 6), (7, 8)])
# Display the array
print("Array of Tuples:")
# Determine and display the shape
shape = array_of_tuples.shape
print("\nShape of Array:", shape)



Array of Tuples:
[[1 2]
[3 4]
[5 6]
[7 8]]

Shape of Array: (4, 2)

Last Updated : 28 Dec, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads