NumPy shape()

The shape() method returns the shape of an array i.e. the number of elements in each dimension.

import numpy as np

array = np.array([[0, 1], [2, 3]])

# return shape of the array shapeOfArray = np.shape(array)
print(shapeOfArray) # Output : (2, 2)

shape() Syntax

The syntax of shape() is:

numpy.shape(array)

shape() Argument

The shape() method takes a single argument:

  • array - an array whose shape is to be determined

shape() Return Value

The shape() method returns the shape of an array as a tuple.


Example 1: Shape of Arrays

import numpy as np

# create 1D and 2D arrays
array1 = np.array([0, 1, 2, 3])
array2 = np.array([[8, 9]])

# shape of array1 shape1 = np.shape(array1)
print('Shape of the first array : ', shape1)
# shape of array2 shape2 = np.shape(array2)
print('Shape of the second array : ', shape2)

Output

Shape of the first array :  (4,)
Shape of the second array :  (1, 2)

Example 2: Shape of Array of Tuples

import numpy as np

# array of tuples
array1 = np.array([(0, 1), ( 2, 3)])

dataType = [('x', int), ('y', int)]

# dtype sets each tuple as an individual array element
array2 = np.array([(0, 1), ( 2, 3)], dtype = dataType)

# shape of array1 shape1 = np.shape(array1)
print('Shape of first array : ', shape1)
# shape of array2 shape2 = np.shape(array2)
print('Shape of second array : ', shape2)

Output

Shape of first array :  (2, 2)
Shape of second array :  (2, )

Here, array1 and array2 are 2-dimensional arrays with tuples as their elements. The shape of array1 is (2, 2). However, the shape of array2 is (2, ), which is one dimensional.

This is because we've passed the dtype argument, which restricts the structure of array2.

array2 contains two elements, each of which is a tuple with two integer values, but each element is treated as a single entity with two fields x and y.

Therefore, array2 is one dimensional with two rows and one column.