NumPy Array Indexing
This lesson explains how to access individual elements of 1-D and 2-D arrays, including how negative indices count backward from the end.
Indexing 1-D Arrays
Just like Python lists, ndarray elements are accessed using square brackets and a zero-based index: the first element is at index 0, the second at index 1, and so on.
Basic 1-D Indexing
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[0]) # 10
print(arr[2]) # 30
print(arr[1] + arr[3]) # 60Negative Indexing
Negative indices count backward from the end of the array: -1 refers to the last element, -2 to the second-to-last, and so on. This avoids the need to know or compute the array's length just to reach its tail.
Indexing from the End
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr[-1]) # 50 (last element)
print(arr[-2]) # 40 (second to last)Indexing 2-D Arrays
A 2-D array needs two indices to reach a single value: the first selects the row, the second selects the column, written as arr[row, col]. This comma-separated form is the idiomatic NumPy way; the chained arr[row][col] syntax also works, but arr[row, col] is more efficient.
Indexing a 2-D Array
import numpy as np
grid = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])
print(grid[0, 0]) # 1 (row 0, col 0)
print(grid[1, 2]) # 7 (row 1, col 2)
print(grid[-1, -1]) # 12 (last row, last column)Exercise: NumPy Array Indexing
For a 1D array arr = np.array([10, 20, 30]), what does arr[0] return?