0
0
NumPydata~10 mins

Negative indexing in NumPy - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Negative indexing
Start with array
Choose index
Is index negative?
NoAccess element at index
Yes
Convert negative index to positive: length + index
Access element at converted index
Return element
Negative indexing means counting from the end of the array. If index is negative, add array length to get the positive index.
Execution Sample
NumPy
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[-1])
print(arr[-3])
Access elements from the end of the array using negative indexes.
Execution Table
StepIndex UsedIs Negative?Converted IndexElement AccessedOutput
1-1Yes5 + (-1) = 4arr[4]50
2-3Yes5 + (-3) = 2arr[2]30
3EndN/AN/AN/AExecution ends
💡 All negative indexes converted and elements accessed; execution ends.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
arr[10, 20, 30, 40, 50][10, 20, 30, 40, 50][10, 20, 30, 40, 50][10, 20, 30, 40, 50]
indexN/A-1-3N/A
converted_indexN/A42N/A
outputN/A5030N/A
Key Moments - 2 Insights
Why do we add the array length to a negative index?
Because negative indexes count from the end, adding the array length converts them to the correct positive index (see execution_table steps 1 and 2).
What happens if the negative index is -1?
It accesses the last element because converted index is length - 1 (step 1 in execution_table).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what element does arr[-3] access?
A20
B30
C40
D50
💡 Hint
Check row 2 in execution_table where index -3 converts to 2 and accesses arr[2].
At which step does the negative index -1 get converted to a positive index?
AStep 1
BStep 2
CStep 3
DNo conversion needed
💡 Hint
See execution_table row 1 where index -1 is converted to 4.
If the array length was 6 instead of 5, what would arr[-1] access?
Aarr[4]
Barr[1]
Carr[5]
Darr[0]
💡 Hint
Negative index -1 converts to length + (-1), so 6 + (-1) = 5.
Concept Snapshot
Negative indexing in numpy:
- Use negative numbers to count from the end.
- Negative index i means access element at length + i.
- Example: arr[-1] is last element.
- Useful to quickly access elements from the back.
- Works like arr[len(arr) + index].
Full Transcript
Negative indexing lets you access elements from the end of a numpy array. When you use a negative index, numpy adds the array length to that index to find the correct position. For example, arr[-1] accesses the last element because it converts to arr[length - 1]. This is helpful to quickly get elements from the back without counting from zero. The execution steps show how negative indexes are converted and used to access elements.