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])   # 60

Negative 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)
ExpressionMeaningExample Result
arr[0]First element of a 1-D array10
arr[-1]Last element of a 1-D array50
grid[1, 2]Row 1, column 2 of a 2-D array7
grid[-1, -1]Last row, last column12
Note: Indexing past the end of an array raises an IndexError, e.g. arr[10] on a 5-element array. Negative indices only protect you from computing the length wrong - they don't extend how many elements exist.
Note: For a 2-D array, grid[1] alone returns the entire second row as a 1-D array - you only need the second index when you want to drill down to one specific element.

Exercise: NumPy Array Indexing

For a 1D array arr = np.array([10, 20, 30]), what does arr[0] return?