Negative indexing
Negative numbers count backwards from the end, so -1 is the last element.
In this page:
Syntax
arr[-1]
arr[-2]
Negative indexing
An index of -1 is the last element, -2 the one before, and so on. This works in every dimension. It saves you from computing len minus one.
Note:
arr[-1] is the idiomatic way to get the last element.
Example: Negative indexing
import numpy as np
a = np.array([5, 10, 15, 20])
print(a[-1], a[-2])
m = np.array([[1, 2], [3, 4]])
print(m[-1, -1])
# Output:
# 20 15
# 4
Related Topics
Common Mistakes
- Using -0 and expecting the last item
- Going beyond -len
- Forgetting negative indices work per axis
Chapter Summary
- -1 is the last element
- Works on every axis
- Range is -len to len-1
- Prevents manual length arithmetic
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: