Negative indexing helps you access elements from the end of a list or array easily. It saves time when you want to get last items without counting the total length.
0
0
Negative indexing in NumPy
Introduction
You want the last element of a data array without knowing its length.
You need to slice the last few rows of a dataset quickly.
You want to access elements from the end in a loop or function.
You are working with time series data and want recent values.
You want to reverse access without creating a reversed copy.
Syntax
NumPy
array[-index]
Index -1 means the last element, -2 means second last, and so on.
This works the same way for 1D and multi-dimensional arrays.
Examples
Prints the last element of the array, which is 50.
NumPy
import numpy as np arr = np.array([10, 20, 30, 40, 50]) print(arr[-1])
Prints the third last element, which is 30.
NumPy
print(arr[-3])
Accesses the last row and second last column, printing 8.
NumPy
matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(matrix[-1, -2])
Sample Program
This program shows how to use negative indexing to get elements from the end of 1D and 2D numpy arrays.
NumPy
import numpy as np # Create a 1D array numbers = np.array([5, 10, 15, 20, 25]) # Access last element using negative index last_element = numbers[-1] # Access second last element second_last = numbers[-2] # Create a 2D array matrix = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) # Access element from last row, last column element = matrix[-1, -1] print(f"Last element in numbers: {last_element}") print(f"Second last element in numbers: {second_last}") print(f"Element from last row and last column in matrix: {element}")
OutputSuccess
Important Notes
Negative indexing is very handy for quick access but be careful not to use an index smaller than -length, or it will cause an error.
It works well with slicing too, like arr[-3:] to get last three elements.
Summary
Negative indexing lets you count from the end of arrays easily.
-1 is the last element, -2 is second last, and so on.
It works for both 1D and multi-dimensional numpy arrays.