np.newaxis for adding dimensions in NumPy - Time & Space Complexity
We want to understand how adding a new dimension with np.newaxis affects the time it takes to run code.
Specifically, how does the work grow when we add dimensions to arrays?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.array([1, 2, 3, 4])
new_arr = arr[:, np.newaxis]
This code adds a new dimension to a 1D array, turning it into a 2D column array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating a view with a new dimension using
np.newaxis. - How many times: No explicit loops or copies; it creates a view instantly.
Adding a new axis does not copy data but changes how the array is viewed.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Very few, constant time |
| 100 | Very few, constant time |
| 1000 | Very few, constant time |
Pattern observation: The time to add a new axis stays almost the same no matter the array size.
Time Complexity: O(1)
This means adding a new axis takes the same small amount of time regardless of array size.
[X] Wrong: "Adding a new axis copies all data and takes longer for bigger arrays."
[OK] Correct: Actually, np.newaxis creates a view without copying data, so it runs quickly no matter the size.
Knowing how array views work helps you write efficient code and answer questions about data handling speed.
What if we used np.reshape instead of np.newaxis? How would the time complexity change?