Inspect arr.shape to get a tuple of exact axis sizes (e.g., (rows, cols)), arr.ndim to get the integer number of dimensions (rank), and arr.size to get the total number of elements across all axes—all of which are $O(1)$ C-level metadata properties on any numpy.ndarray rather than methods requiring parentheses.
Basic Example
import numpy as np
# 1. 2D Matrix (3 rows, 4 columns):
matrix = np.zeros((3, 4))
print("shape:", matrix.shape) # Output: shape: (3, 4)
print("ndim: ", matrix.ndim) # Output: ndim: 2
print("size: ", matrix.size) # Output: size: 12
# 2. 1D Vector (5 elements — note the trailing comma in the 1-tuple):
vec = np.array([10, 20, 30, 40, 50])
print("shape:", vec.shape) # Output: shape: (5,)
print("ndim: ", vec.ndim) # Output: ndim: 1
# 3. 3D Tensor (2 batches, 3 rows, 4 columns):
tensor = np.ones((2, 3, 4))
print("shape:", tensor.shape) # Output: shape: (2, 3, 4)
print("ndim: ", tensor.ndim) # Output: ndim: 3
Key Details & Edge Cases
.shapeand.ndimare attributes, NOT methods (never add()):- Calling
arr.shape()raisesTypeError: 'tuple' object is not callable, andarr.n()raisesTypeError: 'int' object is not callable. Always access them without parentheses (arr.shape,arr.ndim).
- Calling
- 1D
(5,)vs. 2D row(1, 5)vs. 2D column(5, 1)vs. 0D scalar():- 0D scalar (
np.array(42)):arr.shape == ()andarr.ndim == 0(len(arr)raisesTypeError: len() of unsized object, whereasarr.size == 1). - 1D array (
np.array([1, 2, 3])):arr.shape == (3,)(ndim == 1). Unlike 2D(3, 1)or(1, 3)matrices, a 1D array has no orientation; usearr[:, np.newaxis]orarr.reshape(-1, 1)when a library (likescikit-learn) requires a 2D column array.
- 0D scalar (
- Avoid
len(arr)when checking array dimensions:len(arr)only returns the size of the first axis (arr.shape[0]), hiding all remaining axes and crashing on 0D scalars. Usearr.shapefor exact axis lengths andarr.sizefor total element count.
- Inspecting plain Python lists or array-like inputs safely (
np.shape(obj)/np.ndim(obj)):- If an input variable might be a plain Python
listortuplerather than anp.ndarray, callingobj.shaperaisesAttributeError: 'list' object has no attribute 'shape'. Use the top-level functionsnp.shape(obj)andnp.ndim(obj), which work seamlessly on both NumPy arrays and nested Python sequences.
- If an input variable might be a plain Python
- Ragged / inhomogeneous nested lists (
ValueError):- Calling
np.shape([[1, 2], [3]])ornp.array([[1, 2], [3]])in modern NumPy raisesValueError: setting an array element with a sequence. The requested array has an inhomogeneous shapebecause every row along an axis must have identical length.
- Calling
Comparison of NumPy Shape, Dimension & Size Properties
| Attribute / Function | Return Type | Example Output on np.zeros((2, 3, 4)) |
Works on Plain Python list? |
Best Used When |
|---|---|---|---|---|
arr.shape (Recommended) |
tuple[int, ...] |
(2, 3, 4) |
No (use np.shape(lst)) |
Checking exact axis lengths, unpacking rows, cols = arr.shape, or debugging broadcasting errors. |
arr.ndim (Recommended) |
int |
3 |
No (use np.ndim(lst)) |
Validating array rank (e.g., if arr.ndim != 2: raise ValueError(...)). |
arr.size |
int |
24 (2 * 3 * 4) |
No (use np.size(lst)) |
Checking total element count or testing whether an array is empty (arr.size == 0). |
np.shape(obj) / np.ndim(obj) |
tuple[int, ...] / int |
(2, 3, 4) / 3 |
Yes (if rectangular) | Writing helper functions that accept either np.ndarray or regular Python lists without pre-converting. |
len(arr) |
int |
2 (arr.shape[0] only) |
Yes | Iterating over outer-most slices only; avoid for general shape inspection. |
You must log in or register to comment.
