NumPy Array Shape (original) (raw)

Last Updated : 28 Dec, 2023

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.

Python3

import numpy as npy

arr1 = npy.array([[ 1 , 3 , 5 , 7 ], [ 2 , 4 , 6 , 8 ]])

arr2 = npy.array([[[ 1 , 2 ], [ 3 , 4 ]], [[ 5 , 6 ], [ 7 , 8 ]]])

print (arr1.shape)

print (arr2.shape)

**Output:

(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.

python3

import numpy as npy

arr = npy.array([ 2 , 4 , 6 , 8 , 10 ], ndmin = 6 )

print (arr)

print ( 'shape of an array :' , arr.shape)

**Output:

[[[[[[ 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.

Python3

import numpy as np

array_of_tuples = np.array([( 1 , 2 ), ( 3 , 4 ), ( 5 , 6 ), ( 7 , 8 )])

print ( "Array of Tuples:" )

print (array_of_tuples)

shape = array_of_tuples.shape

print ( "\nShape of Array:" , shape)

**Output:

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

Shape of Array: (4, 2)