Skip to content
Related Articles

Related Articles

NumPy Array Shape

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 19 Feb, 2022
Improve Article
Save Article

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. 
 

Example 1: (Printing the shape of the multidimensional array)

Python3




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]]])
 
# printing the shape of arrays
# first element of tuple gives
# dimension of arrays second
# element of tuple gives number
# of element of each dimension
print(arr1.shape)
print(arr2.shape)


Output: 

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

The example above returns (2, 4) and (2,2,2) which means that the arr1 has 2 dimensions and each dimension has 4 elements. Similarly, arr2 has 3 dimensions and each dimension has 2 rows and 2 columns.

Example 2: (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
 
# creating an array of 6 dimension
# using ndim
arr = npy.array([2, 4, 6, 8, 10], ndmin=6)
 
# printing array
print(arr)
 
# verifying the value of last dimension
# as 5
print('shape of an array :', arr.shape)


Output: 

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

In the above example, we verified the last value of dimension as 5.


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!