← Back to NumPy Course | Chapter 4: Indexing & Slicing | Lesson 3 of 7

Negative indexing

Negative numbers count backwards from the end, so -1 is the last element.

In this page:

  1. Negative indexing
Syntax
python
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

python
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
  1. Using -0 and expecting the last item
  2. Going beyond -len
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.