Pass integer arrays as indices to select arbitrary elements or subarrays. Fancy indexing returns copies, unlike basic slicing views.
1D integer array index
import numpy as np
a = np.array([10, 20, 30, 40, 50])
idx = np.array([0, 2, 4])
print(a[idx])
2D fancy indexing
arr[rows, cols] pairs indices element-wise. Useful for extracting scattered pixels or batch-gather operations.
Combined with boolean
You can use boolean masks and integer indices in different steps—avoid mixing in one index tuple unless you understand copy semantics.
Important interview questions and answers
- Q: Fancy vs slice copy?
A: Fancy indexing always copies selected elements. - Q: Negative indices?
A: Work in integer array indices same as single indexing.
Self-check
- Select elements at indices [1, 3, 3] from 1D array.
- Why does fancy indexing return a copy?
Pitfall: Fancy indexing copies—don't assume view semantics.
Interview prep
- Copy?
Integer array indexing returns copy, not view.
- Use case?
Gather scattered elements or reorder rows.