For a 1D array of 5 elements, shape is (5,); for a 2D array with 3 rows and 4 columns, shape is (3, 4); the length of the shape tuple itself equals the number of dimensions. shape is a read-write attribute — assigning a new, compatible tuple to it reshapes the array in place without copying data, as long as the total number of elements stays the same, which is a lower-level alternative to calling np.reshape().
1Understanding ndarray.shape
For a 1D array of 5 elements, shape is (5,); for a 2D array with 3 rows and 4 columns, shape is (3, 4); the length of the shape tuple itself equals the number of dimensions. shape is a read-write attribute — assigning a new, compatible tuple to it reshapes the array in place without copying data, as long as the total number of elements stays the same, which is a lower-level alternative to calling np.reshape().
The trailing comma in a 1D shape like (5,) is not a typo — it's how Python distinguishes a one-element tuple from a plain integer in parentheses, and it's a common point of confusion for people new to NumPy.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape)2Practical Example
Here is a real-world application of ndarray.shape showing how it is used in production NumPy code.
import numpy as np
arr = np.arange(12)
arr.shape = (3, 4)
print(arr)3Best Practices
Follow these guidelines when working with ndarray.shape:
1. Check .shape before performing operations that depend on specific dimensions, like matrix multiplication, to catch mismatches early with a clear error
2. Prefer np.reshape(arr, new_shape) over directly assigning to arr.shape when you want a new array object rather than modifying the existing one in place
3. Use -1 as one dimension when reshaping, either via .shape or np.reshape, to let NumPy calculate that dimension automatically from the total element count
Tip: The trailing comma in a 1D shape like (5,) is not a typo — it's how Python distinguishes a one-element tuple from a plain integer in parentheses, and it's a common point of confusion for people new to NumPy.
import numpy as np
arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape)