Lesson 8 of 60 · python
Indexing, Slicing, and Iterating in NumPy
Duration: 20 minutes
Indexing, Slicing, and Iterating
NumPy provides powerful ways to access sub‑arrays.
1‑D indexing
arr = np.arange(10)
print(arr[3]) # 3
print(arr[-1]) # 9
2‑D slicing
mat = np.arange(1, 13).reshape(3,4)
print(mat)
# Slice rows 0‑1 and columns 1‑3
sub = mat[0:2, 1:4]
print(sub)
Boolean indexing
mask = arr % 2 == 0 # even numbers mask
print(arr[mask]) # [0 2 4 6 8]
Fancy indexing
rows = np.array([0,2])
cols = np.array([1,3])
print(mat[rows, cols]) # [2 12]
Iterating (avoid when possible)
for row in mat:
print(row)
Performance note: Vectorized operations are much faster than Python loops.