Part 01 / Topic 2 of 7
NumPy arrays
A NumPy array is a grid of numbers with one dtype, stored in one contiguous block of memory. That layout is what makes it fast.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6]])
print(a.shape, a.dtype, a.ndim) # (2, 3) int64 2
print(a[0, 2]) # 3 (row 0, column 2)
print(a[1]) # [4 5 6] (whole row 1)
print(a[:, 1]) # [2 5] (column 1 from every row)
Slicing works like lists, but in any number of dimensions:
b = np.arange(6)
print(b) # [0 1 2 3 4 5]
print(b[2:5]) # [2 3 4]
print(b[::-1]) # [5 4 3 2 1 0]
m = np.array([3.0, 7.0, 1.0, 9.0])
print(m[m > 2.5]) # [3. 7. 9.] boolean mask: keep where True
| You need | Call |
|---|---|
| All zeros / ones | np.zeros(3) · np.ones((2, 3)) |
| A range | np.arange(6) · np.linspace(0, 1, 5) |
| Shape and type | a.shape · a.dtype · a.ndim |
| Reshape | a.reshape(3, 2) · a.ravel() |
Watch the dtype: np.array([1, 2, 3]) / 2 silently becomes float64. In Stage 3, float32 vs float64 matters for PyTorch.
🧪 Quick quiz
ahas shape(2, 3). What doesa[:, 1]return?
Show the answer
Column 1 from every row — a 1-D array of length 2. On the array above: [2 5].
Done here? The practice set for Part 1 — 4 exercises with solutions — is on the part page.