Array Slicing
Extract sub-arrays using start:stop:step syntax
Free tier: read the explanation here. Upgrade to Pro for Drills, Speed challenges & Mastery badges.
UpgradeKnowledge Debt detected
You can study this freely — but your score may plateau if these foundations have gaps. The Mastery badge requires them to be solid.
Explanation
Slicing extracts a range of elements. Syntax: start:stop:step (same as Python lists, but extends to multiple dimensions).
1D slicing:
python a = np.array([0, 10, 20, 30, 40, 50]) a[1:4] # [10, 20, 30] (indices 1,2,3 — stop is exclusive) a[:3] # [0, 10, 20] (from start) a[3:] # [30, 40, 50] (to end) a[::2] # [0, 20, 40] (every 2nd) a[::-1] # [50, 40, 30, 20, 10, 0] (reversed)
2D slicing:
python m = np.arange(16).reshape(4, 4) m[1:3, 1:3] # 2×2 center block (rows 1-2, cols 1-2) m[:2, :] # first 2 rows, all columns m[:, ::2] # all rows, every other column
Important: NumPy slices return views not copies. Modifying a slice modifies the original.
Examples
2D slice extracts a sub-matrix
Rows 1-2 and columns 1-2
import numpy as np
m = np.arange(16).reshape(4, 4)
print(m)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]
# [12 13 14 15]]
print(m[1:3, 1:3])
# [[ 5 6]
# [ 9 10]]How well did you understand this?
Next in NumPy
Array Operations