Skip to content
masterclassBuddyTech Buzz5 fresh blogs · 5:00 AM IST

NumPy · Pipe

ndarray.shape

ndarray.shape gives an array's dimensions as a tuple. Direct assignment can request an in-place reshape, but ndarray.reshape is the preferred approach.

How it works

ndarray.shape exposes an array's dimensions as a tuple. Although assigning a tuple to this property can attempt an in-place reshape, NumPy recommends ndarray.reshape instead; in-place assignment fails when reshaping requires a copy.

Syntax

ndarray.shape

Returns

A tuple of array dimensions.

Key points

  • The property represents an array's dimensions as a tuple, with one value for each axis.
  • Read arr.shape to inspect the current dimensions without changing the array.
  • A tuple assignment can request an in-place reshape, though this is discouraged for new code.
  • A single -1 dimension can be used when assigning or requesting a shape; NumPy infers that dimension.

Common mistakes

  • Do not assign to arr.shape for reshaping in new code; use ndarray.reshape because direct shape assignment is deprecated.
  • Direct in-place reshaping is not guaranteed to work when the requested layout requires a copy.

Example: Read and change an array shape

import numpy as np

x = np.array([1, 2, 3, 4])
print(x.shape)        # (4,)

x = x.reshape(2, 2)
print(x.shape)        # (2, 2)

Read an array's dimensions with shape; use reshape for the preferred way to create a different shape.

When to use it

Check dimensionality

Inspecting data before numerical operations

Confirm expected axes and sizes

Validating inputs to a computation

Reshape with `ndarray.reshape`

Changing an array's view or layout when appropriate

Interview questions

QWhat does ndarray.shape return?

It returns the array's dimensions as a tuple. For example, a one-dimensional array with four elements has shape (4,), while an array with dimensions 2, 3, and 4 has shape (2, 3, 4).

Follow-up: How should an array be reshaped in modern NumPy? Use ndarray.reshape, which is the preferred approach rather than assigning to arr.shape.

QWhat happens when a tuple is assigned to arr.shape?

Assigning a tuple to arr.shape attempts to reshape the array in place. The operation fails if a copy would be required, so it is not a general replacement for reshape.

Follow-up: What does a -1 dimension do? Its value is inferred from the array size and the other dimensions.

QHow should shape tuples be interpreted?

A shape tuple contains one dimension size per axis, so (2, 3, 4) describes a three-dimensional array. The product of the dimensions must match the number of elements when changing shape.

Follow-up: Why can in-place reshaping fail even when the element count matches? The existing memory layout may require a copy.

  • numpy.reshape
  • ndarray.reshape

Source: numpy.ndarray.shape#. Checked 2026-10-15.