NumPy indexing extends Python slicing to multiple dimensions. Slices return views when possible—mutating a slice can change the original array.
1D indexing
import numpy as np
a = np.array([10, 20, 30, 40, 50])
print(a[0], a[-1], a[1:4])
2D indexing
arr[row, col]— single elementarr[row, :]— entire rowarr[:, col]— entire columnarr[0:2, 1:3]— submatrix slice
Views vs copies
Basic slicing usually creates a view sharing memory. Fancy indexing (integer arrays) returns a copy. Use .copy() when you need independence.
Important interview questions and answers
- Q: a[1:4] inclusive?
A: Stop index exclusive—elements at indices 1, 2, 3. - Q: Why care about views?
A: In-place edits to slices affect parent array—subtle bugs in pipelines.
Self-check
- Extract the second column of a 2D array.
- Does slicing always copy?
Pitfall: Slicing returns views—mutations affect the parent array.
Interview prep
- View?
Basic slices share memory—mutations affect parent.
- 2D index?
arr[row, col]—comma separates axes.