0
0
NumPydata~5 mins

Indexing returns views not copies in NumPy - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Indexing returns views not copies
O(1)
Understanding Time 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.

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Slice indexing (view creation) and element assignment
  • How many times: Once each (constant time)
How Execution Grows With Input

When we take a slice, numpy does not copy data but creates a view in constant time.

Input Size (n)Approx. Operations
10Constant (~5 operations)
100Constant (~5 operations)
1000Constant (~5 operations)

Pattern observation: The time to create a view is constant O(1), independent of slice size, no data copying happens.

Final Time Complexity

Time Complexity: O(1)

This means the time is constant regardless of the size of the slice (k), with no copying cost.

Common Mistake

[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.

Interview Connect

Knowing when numpy makes views or copies helps you write faster code and answer questions about data handling clearly.

Self-Check

"What if we used fancy indexing (like a list of indices) instead of a slice? How would the time complexity change?"