How to return the shape of an array in Python

Overview

The ma.shape() method in the NumPy module in Python is used to obtain the shape of a given array.

The shape of an array is the number of elements found in each axis (rows and columns) of the array. For example, an array with a shape, (2, 3), means that the array has 2 rows that contain 3 elements each.

Syntax

The ma.shape() function takes the syntax below:

ma.shape(obj)
Syntax for the ma.shape() method

Parameter value

The ma.shape() function takes a single parameter value, obj, which represents the input array.

Return value

The ma.shape() function returns the shape of the input array.

Example

Let's look at the code below:

import numpy as np
import numpy.ma as ma
# creating an array
a = np.array([1, 2, 3, 4, 5, 6])
b = np.array([[1, 2, 3], [4, 5, 6]])
# implementing the ma.shape() method
c = ma.shape(a)
d = ma.shape(b)
print(a)
print("This is the shape of array a: ", c)
print(b)
print("This is the shape of array b: ", d)

Explanation

  • Line 1: We import the numpy module.

  • Line 2: We import the numpy.ma module.

  • Lines 4 and 5: We create the input arrays, a and b, using the array() function.

  • Lines 8 and 9: We apply the ma.shape() function on a and b and pass their respective results to c and d.

  • Lines 11 and 15: We return the arrays a and b and their respective shapes c and d.

Free Resources