How to Use Negative Indexing in NumPy Arrays
In NumPy, you can use
negative indexing to access elements from the end of an array by using negative numbers like -1 for the last element, -2 for the second last, and so on. This works similarly to Python lists and helps quickly select elements counting backward.Syntax
Negative indexing in NumPy uses a negative integer inside square brackets to select elements from the end of an array.
array[-1]: selects the last elementarray[-2]: selects the second last elementarray[-n]: selects the nth element from the end
python
element = array[-1]Example
This example shows how to create a NumPy array and access elements using negative indexing to get the last and second last values.
python
import numpy as np array = np.array([10, 20, 30, 40, 50]) last_element = array[-1] second_last_element = array[-2] print(f"Last element: {last_element}") print(f"Second last element: {second_last_element}")
Output
Last element: 50
Second last element: 40
Common Pitfalls
One common mistake is using a negative index that is out of range, which causes an IndexError. For example, if the array length is 5, using -6 will fail.
Also, negative indexing works element-wise, but when slicing, be careful with start and stop positions as negative indices count from the end.
python
import numpy as np array = np.array([1, 2, 3, 4, 5]) # Wrong: IndexError because -6 is out of range # print(array[-6]) # Right: Use valid negative index print(array[-5]) # prints 1 # Slicing with negative indices print(array[-3:]) # prints last 3 elements [3 4 5]
Output
1
[3 4 5]
Quick Reference
| Negative Index | Meaning | Example with array [10, 20, 30, 40, 50] |
|---|---|---|
| -1 | Last element | 50 |
| -2 | Second last element | 40 |
| -3 | Third last element | 30 |
| -len(array) | First element | 10 |
Key Takeaways
Negative indexing in NumPy accesses elements from the end using negative numbers.
Use -1 for the last element, -2 for the second last, and so on.
Negative indices must be within the array length to avoid errors.
Negative indexing works with slicing but be careful with start and stop positions.
It is a quick way to access elements without calculating positive indices.