Cheat sheets

Everything you keep looking up, on one page

Fast reference for the tools and terms you use every day — Python, NumPy, pandas, scikit-learn, PyTorch, prompting, and the ML concepts interviewers ask about. Bookmark it. Each sheet links to the lesson that teaches it in full.

Python essentials

The 20% of syntax you use 80% of the time.

xs = [1, 2, 3]
List — ordered, mutable
[x * 2 for x in xs if x > 1]
List comprehension (filter + map)
d = {'a': 1}; d.get('b', 0)
Dict lookup with default
for i, v in enumerate(xs):
Index + value together
for a, b in zip(xs, ys):
Iterate two lists in lockstep
def f(x, *args, **kwargs):
Variadic positional + keyword args
f = lambda x: x + 1
Anonymous one-line function
with open('f.txt') as fh:
Auto-closes the file
sorted(xs, key=lambda x: -x)
Sort by a custom key
from collections import Counter
Counter, defaultdict, deque
Full lesson →

NumPy

Vectorised arrays — the base of everything numeric.

import numpy as np
The universal import
a = np.array([[1, 2], [3, 4]])
2×2 array
np.zeros((3, 4)), np.ones(5)
Filled arrays
np.arange(0, 1, 0.1)
Range with a step
np.linspace(0, 1, 11)
11 evenly spaced points
a.shape, a.dtype, a.reshape(4)
Inspect & reshape
a @ b
Matrix multiply
a.sum(axis=0), a.mean(axis=1)
Reduce along an axis
a[a > 2]
Boolean mask select
np.random.seed(0)
Reproducible randomness
Full lesson →

pandas

Load, clean, and slice tabular data.

df = pd.read_csv('data.csv')
Load a CSV
df.head(), df.info(), df.describe()
First look at any dataset
df['col'], df[['a', 'b']]
Select column(s)
df.loc[rows, cols]
Label-based indexing
df.iloc[0:5, 0:2]
Position-based indexing
df[df['age'] > 30]
Filter rows by condition
df.groupby('city')['sales'].mean()
Split-apply-combine
df.isna().sum()
Count missing per column
df.fillna(0), df.dropna()
Handle missing values
df.merge(other, on='id')
SQL-style join
Full lesson →

scikit-learn

The same fit/predict shape for every classic model.

from sklearn.model_selection import train_test_split
Split first — always
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, stratify=y)
Held-out test set
from sklearn.ensemble import RandomForestClassifier
A strong default model
model.fit(X_tr, y_tr)
Train
preds = model.predict(X_te)
Predict
model.predict_proba(X_te)
Class probabilities
from sklearn.metrics import classification_report
Precision/recall/F1 at once
from sklearn.preprocessing import StandardScaler
Fit on train only
from sklearn.pipeline import make_pipeline
Bundle transforms + model
cross_val_score(model, X, y, cv=5)
5-fold cross-validation
Full lesson →

PyTorch

The training loop that every deep-learning project shares.

import torch, torch.nn as nn
Core imports
x = torch.tensor([1., 2.], requires_grad=True)
Autograd tensor
device = 'cuda' if torch.cuda.is_available() else 'cpu'
Pick GPU if present
model = nn.Sequential(nn.Linear(4, 16), nn.ReLU(), nn.Linear(16, 3))
A small MLP
loss_fn = nn.CrossEntropyLoss()
Classification loss
opt = torch.optim.Adam(model.parameters(), lr=1e-3)
Optimiser
opt.zero_grad()
1 · clear old gradients
loss = loss_fn(model(xb), yb); loss.backward()
2 · forward + backprop
opt.step()
3 · update weights
with torch.no_grad(): model.eval()
Inference mode
Full lesson →

Prompt engineering

Patterns that reliably get better LLM output.

Role: 'You are an expert X…'
Set the persona & context
Be specific: format, length, audience
Vague in → vague out
Give 2–3 examples (few-shot)
Show the pattern you want
'Think step by step.'
Chain-of-thought for reasoning
Return JSON: {"answer": …}
Constrain the output shape
Ground it: 'Using only the text below…'
Reduce hallucination (RAG)
'If unsure, say you don't know.'
Permission to abstain
Lower temperature for facts, raise for ideas
Control randomness
Delimit input with ``` or <tags>
Separate instructions from data
Iterate: test, tweak, keep an eval set
Prompting is empirical
Full lesson →

ML concepts

The definitions interviewers expect you to know cold.

Supervised vs unsupervised
Labelled targets vs finding structure
Overfitting
Great on train, bad on new data
Bias–variance
Too simple vs too sensitive to noise
Precision
Of flagged, how many were right
Recall
Of the real positives, how many caught
F1
Harmonic mean of precision & recall
Regularization (L1/L2)
Penalise big weights → less overfit
Gradient descent
Step downhill on the loss
Embedding
Meaning as a vector; near = similar
RAG
Retrieve facts, then let the LLM answer
Full lesson →

Git & environments

Ship your work — the commands you actually type.

python -m venv .venv && source .venv/bin/activate
Isolated environment
pip install numpy pandas scikit-learn
Install packages
pip freeze > requirements.txt
Pin your deps
git init && git add . && git commit -m 'init'
Start a repo
git checkout -b feature
Work on a branch
git status, git diff, git log --oneline
See what changed
git push -u origin feature
Publish the branch
jupyter notebook
Interactive exploration
%matplotlib inline
Show plots in notebooks
.gitignore: .venv/ __pycache__/ *.ipynb_checkpoints
Keep junk out of git
Full lesson →

These are the highlights — the real understanding is in thelessons. Prepping for interviews? Pair this with theinterview questions.