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 array
my_array = array([[1, 2, 3, 4], [5, 6, 7, 8]])
# to return the shape of the array
print(my_array.shape)

Explanation

  • Line 1: We import the array from the numpy library.
  • Line 4: We create an array using the array() method.
  • Line 7: We implement the shape attribute to determine the shape of the array my_array and 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 array
my_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.

Free Resources