What is the shape attribute of numpy in Python?
Overview
The shape attribute in numpy is used to return a tuple with the index numbers representing the dimension or shape of the given array.
Syntax
array.shape
Parameter
array.shape is an attribute and therefore takes no parameter value.
Return value
array.shape returns the shape [dimension of the 2D array (row, column)] of a given array.
Example
from numpy import array# creating an arraymy_array = array([[1, 2, 3, 4], [5, 6, 7, 8]])# to return the shape of the arrayprint(my_array.shape)
Explanation
- Line 1: We import the
arrayfrom thenumpylibrary. - Line 4: We create an array using the
array()method. - Line 7: We implement the
shapeattribute to determine the shape of the arraymy_arrayand print the output.
The output of the code is (2,4), which means that the array my_array we created is a two-dimensional array. The first has 2 elements while the second has 4 elements.
Let’s try out another example:
Example
from numpy import arraymy_array = array([1, 2, 3, 4])print(my_array.shape)
Code explanation
The output of the code above (4,) means that the array my_array is a one-dimensional array with 4 elements.