Before You Start
- Required knowledge
- Python lists, loops, functions, and basic arithmetic.
- Libraries used
- NumPy
- Dataset and source
- Small arrays and random matrices created in the notebook; no external dataset.
- Expected output
- Vectorized array operations, shape checks, timing comparisons, and a PCA calculation.
NumPy Deep Dive โ Theory & Concepts
Read this before attempting the exercises. This guide covers the core NumPy concepts you'll need, with visual explanations and code examples.
1. Why NumPy?
Python lists are flexible but slow for numerical computation. NumPy arrays are:
- โContiguous in memory โ no pointer chasing
- โTyped โ every element is the same dtype (float64, int32, etc.)
- โVectorized โ operations apply element-wise in C, not Python loops
# Python list: ~100x slower for large arrays
python_list = [i**2 for i in range(1_000_000)]
# NumPy: vectorized, runs in C
import numpy as np
arr = np.arange(1_000_000) ** 2 # ~100x faster
Memory Layout: Row-Major (C) vs Column-Major (Fortran)
Row-major (C order): Column-major (F order):
+---+---+---+ +---+---+---+
| 1 | 2 | 3 | > memory | 1 | 3 | 5 | > memory
+---+---+---+ +---+---+---+
| 4 | 5 | 6 | | 2 | 4 | 6 |
+---+---+---+ +---+---+---+
Memory: [1,2,3,4,5,6] Memory: [1,2,3,4,5,6]
FAANG Interview Tip: When asked "why is NumPy faster than Python lists?", mention: contiguous memory, no type checking per element, SIMD vectorization, and cache locality.
2. Array Creation & Shapes
import numpy as np
# From lists
a = np.array([1, 2, 3]) # shape: (3,)
b = np.array([[1, 2], [3, 4]]) # shape: (2, 2)
# Common constructors
np.zeros((3, 4)) # 3ร4 matrix of zeros
np.ones((2, 3)) # 2ร3 matrix of ones
np.eye(3) # 3ร3 identity matrix
np.arange(0, 10, 2) # [0, 2, 4, 6, 8]
np.linspace(0, 1, 5) # [0.0, 0.25, 0.5, 0.75, 1.0]
np.random.randn(3, 4) # 3ร4 matrix of standard normal values
Shape vs Reshape
Original: shape (6,)
[1, 2, 3, 4, 5, 6]
Reshaped to (2, 3): Reshaped to (3, 2):
+---+---+---+ +---+---+
| 1 | 2 | 3 | | 1 | 2 |
+---+---+---+ +---+---+
| 4 | 5 | 6 | | 3 | 4 |
+---+---+---+ +---+---+
| 5 | 6 |
+---+---+
Key rule: reshape doesn't copy data โ it creates a view. The total number of elements must stay the same.
3. Indexing & Slicing
NumPy supports powerful indexing beyond Python lists:
arr = np.array([[10, 20, 30],
[40, 50, 60],
[70, 80, 90]])
arr[0, 1] # 20 โ single element
arr[0] # [10, 20, 30] โ first row
arr[:, 1] # [20, 50, 80] โ second column
arr[1:, :2] # [[40, 50], [70, 80]] โ submatrix
Boolean Indexing (Masking)
arr = np.array([1, -2, 3, -4, 5])
mask = arr > 0 # [True, False, True, False, True]
arr[mask] # [1, 3, 5] โ only positive values
arr[arr > 0] = 0 # set all positives to 0
Fancy Indexing
arr = np.array([10, 20, 30, 40, 50])
indices = [0, 3, 4]
arr[indices] # [10, 40, 50]
FAANG Gotcha: Boolean indexing returns a copy, but basic slicing returns a view. Modifying a view modifies the original!
a = np.array([1, 2, 3, 4])
b = a[:2] # view โ shares memory
b[0] = 99 # a is now [99, 2, 3, 4] โ ๏ธ
c = a[a > 2] # copy โ independent
c[0] = 0 # a is unchanged
4. Broadcasting
Broadcasting lets NumPy operate on arrays of different shapes without copying data.
Rules:
- โAlign shapes from the right
- โDimensions match if they're equal OR one of them is 1
- โMissing dimensions are treated as 1
Shape (3, 4) + Shape (4,) > works! (4,) becomes (1, 4) > broadcast to (3, 4)
Shape (3, 4) + Shape (3,) > ERROR! trailing dimensions 4 ! 3
Shape (3, 1) + Shape (1, 4) > works! result is (3, 4)
Visual Example:
A: shape (3, 1) B: shape (1, 4) A + B: shape (3, 4)
+---+ +---+---+---+---+ +---+---+---+---+
| 1 | + | 10| 20| 30| 40| = | 11| 21| 31| 41|
+---+ +---+---+---+---+ +---+---+---+---+
| 2 | | 12| 22| 32| 42|
+---+ +---+---+---+---+
| 3 | | 13| 23| 33| 43|
+---+ +---+---+---+---+
Interview Tip: Broadcasting is how ML frameworks compute things like "subtract the mean from every row" efficiently:
X = np.random.randn(1000, 5) # 1000 samples, 5 features
mean = X.mean(axis=0) # shape (5,)
X_centered = X - mean # broadcasting! (1000, 5) - (5,) โ (1000, 5)
5. Vectorized Operations & Aggregations
Never use Python loops on NumPy arrays. Use vectorized operations instead:
a = np.array([1, 2, 3, 4])
b = np.array([10, 20, 30, 40])
# Element-wise operations
a + b # [11, 22, 33, 44]
a * b # [10, 40, 90, 160]
a ** 2 # [1, 4, 9, 16]
np.sqrt(a) # [1.0, 1.414, 1.732, 2.0]
np.exp(a) # [2.718, 7.389, 20.086, 54.598]
Aggregations with axis
X = np.array([[1, 2, 3],
[4, 5, 6]])
X.sum() # 21 โ total
X.sum(axis=0) # [5, 7, 9] โ sum down columns
X.sum(axis=1) # [6, 15] โ sum across rows
X.mean(axis=0) # [2.5, 3.5, 4.5] โ column means
X.max(axis=1) # [3, 6] โ row maxima
axis=0: v down rows (collapse rows)
axis=1: > across columns (collapse columns)
col0 col1 col2
v v v
row0 [ 1, 2, 3 ] > axis=1 sum = 6
row1 [ 4, 5, 6 ] > axis=1 sum = 15
v v v
5 7 9 < axis=0 sum
FAANG Gotcha: axis=0 means "operate along axis 0 (rows)" which collapses that axis. Many candidates confuse this.
6. Linear Algebra Essentials
A = np.array([[1, 2], [3, 4]])
B = np.array([[5, 6], [7, 8]])
# Matrix multiplication (NOT element-wise)
A @ B # or np.dot(A, B)
# [[19, 22],
# [43, 50]]
# Transpose
A.T # [[1, 3], [2, 4]]
# Inverse
np.linalg.inv(A) # [[-2, 1], [1.5, -0.5]]
# Determinant
np.linalg.det(A) # -2.0
# Eigenvalues
vals, vecs = np.linalg.eig(A)
Key for ML: Matrix multiplication is the backbone of neural networks. Every layer computes output = X @ W + b.
7. Common Patterns in ML
Normalize features (zero mean, unit variance)
X = np.random.randn(100, 5)
X_norm = (X - X.mean(axis=0)) / X.std(axis=0)
Softmax function
def softmax(z):
exp_z = np.exp(z - z.max()) # subtract max for numerical stability
return exp_z / exp_z.sum()
Euclidean distance matrix
def pairwise_distances(X):
# X: shape (N, D)
sq = np.sum(X**2, axis=1, keepdims=True) # (N, 1)
return np.sqrt(sq + sq.T - 2 * X @ X.T) # (N, N)
Summary
| Concept | Key Takeaway |
|---|---|
| Why NumPy | Contiguous memory, vectorized C ops, cache-friendly |
| Views vs Copies | Slicing = view (shared memory), boolean indexing = copy |
| Broadcasting | Align from right, dimensions must be equal or 1 |
| axis parameter | axis=0 collapses rows, axis=1 collapses columns |
| Vectorization | Never loop โ use +, *, @, np.sum(), etc. |
Now you're ready to attempt the exercises. Switch to the Exercise tab and start coding!
SVD Visual

Use SVD to understand low-rank structure and dimensionality reduction (M = U\Sigma V^T).
Ready to practice?
Setup
Section 1 โ ndarray Fundamentals
Task 1.1: Array Creation & Shapes
ndarray Fundamentals
Section 1 โ ndarray Fundamentals
Task 1.1: Array Creation & Shapes
dtype & Memory
Explain:
- โWhat does
.shaperepresent? - โWhy does contiguous memory matter?
Section 1.2 โ dtype & Memory
Task 1.2: Compare memory usage
Indexing, Views & Copies
Interview Question:
Why does dtype selection matter in large ML pipelines?
Section 2 โ Indexing, Views & Copies
Task 2.1: Views vs Copies
Boolean Masking
Explain:
- โWhy did the original array change (or not)?
Section 2.2 โ Boolean Masking
Task 2.2: Boolean masking
Broadcasting
Section 3 โ Broadcasting
Task 3.1: Broadcasting Rules
Broadcasting Trap
Explain broadcasting step-by-step.
Section 3.2 โ Broadcasting Trap
Task 3.2: Fix a broadcasting trap
Vectorization vs Loops
What was wrong with the original shapes?
Section 4 โ Vectorization vs Loops
Task 4.1: Loop vs Vectorized
Why is vectorization faster?
Task 4.2: Pairwise Distance (FAANG Classic)
Numerical Stability
Section 5 โ Numerical Stability
Task 5.1: Softmax
Softmax converts logits into probabilities:
Stable form (subtract max logit in each row):
Linear Algebra
Why does subtracting max work?
Section 6 โ Linear Algebra
Task 6.1: Matrix Multiplication
Explain difference between dot, @, and matmul.
Task 6.2: Solving Linear Systems
Performance & Memory
Section 7 โ Performance & Memory
Task 7.1: In-Place Operations
Task 7.2: Strides
Mini Case Study
Section 8 โ Mini Case Study
Task 8.1: Mini case study (NumPy PCA)

