Indexing & Slicing
One-dimensional NumPy arrays index and slice exactly like Python lists. Once you move into two dimensions, the syntax changes slightly — and it's worth learning the NumPy way rather than the list way.
1D indexing and slicing: same as lists
>>> familiar territory
import numpy as np values = np.array([10, 20, 30, 40, 50]) print(values[0]) print(values[-1]) print(values[1:3])
Output
10 50 [20 30]
2D indexing: one set of brackets, a comma inside
For a 2D array, NumPy lets you index both dimensions in a single pair of brackets: array[row, col], rather than chaining two separate index operations:
>>> a 3x3 grid
grid = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) print(grid[1, 2]) print(grid[0]) print(grid[:, 1])
Output
6 [1 2 3] [2 5 8]
grid[1, 2] reads row 1, column 2 — the value 6. grid[0] with no column specified returns the entire first row. grid[:, 1] uses : to mean "every row," so it pulls out the whole second column instead.
Note:
grid[1][2] also works and gives the same answer, but it's doing two separate steps — grid[1] creates a temporary 1D array, then [2] indexes into that. grid[1, 2] is a single indexing operation and is both faster and the idiomatic NumPy style; prefer the comma form.