Indexing returns views not copies in NumPy - Time & Space Complexity
When we use indexing in numpy, it often gives us a view of the data, not a full copy.
We want to see how this affects the time it takes to access or change data.
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.arange(1000000)
sub_arr = arr[1000:2000]
sub_arr[0] = 999
This code creates a large array, then takes a slice which is a view, and changes one element in the slice.
- Primary operation: Slice indexing (view creation) and element assignment
- How many times: Once each (constant time)
When we take a slice, numpy does not copy data but creates a view in constant time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Constant (~5 operations) |
| 100 | Constant (~5 operations) |
| 1000 | Constant (~5 operations) |
Pattern observation: The time to create a view is constant O(1), independent of slice size, no data copying happens.
Time Complexity: O(1)
This means the time is constant regardless of the size of the slice (k), with no copying cost.
[X] Wrong: "Indexing always makes a full copy of the data, so it takes a long time."
[OK] Correct: Actually, numpy usually creates a view, which is fast and shares data with the original array.
Knowing when numpy makes views or copies helps you write faster code and answer questions about data handling clearly.
"What if we used fancy indexing (like a list of indices) instead of a slice? How would the time complexity change?"