Array attributes (shape, dtype, ndim, size) in NumPy - Time & Space Complexity
We want to understand how fast we can get information about a NumPy array's structure and type.
How does the time to access attributes like shape or size change as the array grows?
Analyze the time complexity of accessing array attributes.
import numpy as np
arr = np.arange(1000).reshape(100, 10)
shape = arr.shape
ndim = arr.ndim
size = arr.size
dtype = arr.dtype
This code creates a 2D array and reads its shape, number of dimensions, total size, and data type.
Look for any repeated work when accessing these attributes.
- Primary operation: Accessing stored metadata of the array.
- How many times: Each attribute is accessed once, no loops or traversals.
Accessing these attributes does not depend on array size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays the same no matter how big the array is.
Time Complexity: O(1)
This means accessing these attributes takes the same short time regardless of array size.
[X] Wrong: "Getting the size or shape takes longer for bigger arrays because it counts elements."
[OK] Correct: NumPy stores this information when the array is created, so it just reads it instantly without counting.
Knowing that attribute access is fast helps you write efficient code and explain performance clearly in interviews.
"What if we tried to compute the sum of all elements instead of just accessing size? How would the time complexity change?"