Jupyter Notebook cheat sheet
A scannable Jupyter Notebook reference: 30 short snippets across 10 topics, each linking back to the lesson it came from.
At a glance
| Topic | What it covers | |
|---|---|---|
| Notebook fundamentals | A notebook is a document of cells plus a kernel: a live Python process holding all your variables. Cells can be code or | lesson |
| A notebook workflow that scales | The single most valuable habit: the moment a cell contains logic you might reuse, move it into src/ and import it | lesson |
| Installing JupyterLab and managing kernels | Every Jupyter front end talks the same kernel protocol: the browser sends code, a separate process executes it and | lesson |
| Markdown, LaTeX and rich output | A Markdown cell is rendered, not executed. Double-click to edit, Shift+Enter to render. Headings build the notebook | lesson |
| Magics: line, cell and shell commands | Magics are not Python. A line magic starts with one percent sign and applies to the rest of that line; a cell magic | lesson |
| Visualisation inside notebooks | Setting figure.figsize and dpi once in a setup cell is better than repeating them in every plot, and it makes exported | lesson |
| Notebooks vs scripts: jupytext, nbconvert and papermill | jupytext makes an .ipynb file and a readable text file two views of the same document. You edit either; the other is | lesson |
| Version control, diffs and reproducible output | An .ipynb is JSON containing source, execution counts, outputs, metadata and base64 images. Changing one number in a | lesson |
| Debugging and the hidden-state trap | Logging beats printing: messages carry timestamps and levels, survive %%capture handling, and can be redirected to a | lesson |
| Beyond local notebooks: Colab, Voila and Quarto | Hosted notebooks remove installation friction, which is genuinely valuable for teaching and for one-off GPU work. They | lesson |
Quick snippets
Notebook fundamentals
Cells and kernels
pip install notebook jupyterlab
jupyter lab # the modern interface
jupyter notebook # the classic interface
jupyter nbconvert --to html report.ipynb
Execution order is not document order
[3] total = 0
[1] total += 10 # ran BEFORE the line above
[7] print(total) # 10 - which line defines total?
Magics worth knowing
%timeit sum(range(1000)) # benchmark a line
%%time # time a whole cell
%matplotlib inline
%run script.py # execute a file in the kernel
!pip install pandas # shell command
%reload_ext autoreload
%autoreload 2 # pick up edits to imported modulesFull lesson: Notebook fundamentals →
A notebook workflow that scales
Structure of a project
project/
notebooks/
01-explore.ipynb
02-report.ipynb
src/
__init__.py
load.py # reusable functions the notebook imports
data/
raw/ # never edited by hand
processed/
requirements.txt
README.md
Structure of a project
import sys
sys.path.append("..") # so "import src.load" works from notebooks/
from src.load import read_sales
df = read_sales("../data/raw/sales.csv")
Reproducibility
from pathlib import Path
ROOT = Path.cwd().parent
DATA = ROOT / "data" / "raw" / "sales.csv"Full lesson: A notebook workflow that scales →
Installing JupyterLab and managing kernels
Install into the environment that has your libraries
python -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install jupyterlab ipykernel numpy pandas
jupyter lab
Registering and listing kernels
# register the active environment under a readable name
python -m ipykernel install --user --name sales-analysis --display-name "Python (sales)"
jupyter kernelspec list # where each kernel points
jupyter kernelspec remove sales-analysis
Registering and listing kernels
# verify inside a notebook which interpreter is really running
import sys
print(sys.executable)
print(sys.version)
# and where it will look for packages
print(sys.path[:3])Full lesson: Installing JupyterLab and managing kernels →
Markdown, LaTeX and rich output
Markdown cells
## Method
We measured throughput over **three** runs.
| Run | Tokens/s |
|-----|----------|
| 1 | 41.2 |
| 2 | 43.0 |

Maths with LaTeX
The mean squared error is $\frac{1}{n}\sum_{i=1}^{n}(y_i - \hat{y}_i)^2$.
$$
\hat{\beta} = (X^{\mathsf{T}}X)^{-1}X^{\mathsf{T}}y
$$
Rich output objects
from IPython.display import display, Markdown, HTML, Image, Audio, Latex, JSON
display(Markdown("**Bold** text built at runtime"))
display(HTML("<table><tr><td>a</td><td>b</td></tr></table>"))
display(Image(filename="img/plot.png", width=320))
display(Latex(r"\int_0^1 x^2\,dx = \tfrac{1}{3}"))
display(JSON({"rows": 3, "ok": True}))Full lesson: Markdown, LaTeX and rich output →
Magics: line, cell and shell commands
The ones you will actually use
%timeit -n 100 -r 5 sorted(data)
%%time
model.fit(X_train, y_train)
%%capture noisy
plot_everything() # output stored in "noisy", nothing rendered
%run preprocess.py # definitions land in the notebook namespace
%load_ext autoreload
%autoreload 2 # re-import edited modules automatically
The ones you will actually use
%%bash
set -euo pipefail
for f in data/raw/*.csv; do
wc -l "$f"
done
Writing your own magic
from IPython.core.magic import register_line_magic, register_cell_magic
@register_line_magic
def sql(line):
"""Run a query and return a DataFrame."""
import pandas as pd, sqlite3
con = sqlite3.connect("app.db")
return pd.read_sql_query(line, con)
%sql SELECT status, count(*) FROM orders GROUP BY statusFull lesson: Magics: line, cell and shell commands →
Visualisation inside notebooks
Choosing a backend
%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (7, 3.5)
plt.rcParams["figure.dpi"] = 120 # sharpness in the notebook
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set(xlabel="time (s)", ylabel="throughput", title="Steady state")
fig.tight_layout()
plt.show()
pandas and seaborn
import pandas as pd, seaborn as sns
pd.set_option("display.max_columns", 50)
pd.set_option("display.float_format", "{:,.2f}".format)
df.groupby("region")["revenue"].sum().plot.bar()
sns.set_theme(style="whitegrid")
sns.scatterplot(data=df, x="spend", y="revenue", hue="region")
Interactive libraries
import plotly.express as px
px.scatter(df, x="spend", y="revenue", color="region",
hover_data=["campaign"]).show()
# Bokeh
from bokeh.plotting import figure, output_notebook, show
output_notebook()
p = figure(width=500, height=300, title="Latency")
p.line(x, y)
show(p)Full lesson: Visualisation inside notebooks →
Notebooks vs scripts: jupytext, nbconvert and papermill
Paired scripts with jupytext
pip install jupytext
# create the pairing once, per notebook
jupytext --set-formats ipynb,py:percent notebooks/analysis.ipynb
# or convert in a batch
jupytext --to py:percent notebooks/*.ipynb
# produce a Markdown view for review
jupytext --to md notebooks/analysis.ipynb
nbconvert exporters
jupyter nbconvert --to html --execute --ExecutePreprocessor.timeout=600 analysis.ipynb
jupyter nbconvert --to slides --post serve talk.ipynb
Parameterised runs with papermill
# a cell tagged "parameters" in the notebook defines the defaults
month = "2026-08"
region = "all"Full lesson: Notebooks vs scripts: jupytext, nbconvert and papermill →
Version control, diffs and reproducible output
Stripping outputs automatically
pip install nbstripout
nbstripout --install # configures the git filter for this repository
# check it is wired up
git config --get filter.nbstripout.clean
# strip a single file manually
nbstripout analysis.ipynb
Stripping outputs automatically
# .gitattributes
*.ipynb filter=nbstripout
*.ipynb diff=jupyternotebook
*.ipynb merge=jupyternotebook
Deterministic output
import random, numpy as np
SEED = 42
random.seed(SEED)
np.random.seed(SEED)
# set display options that affect output but not results
np.set_printoptions(precision=4, suppress=True)Full lesson: Version control, diffs and reproducible output →
Debugging and the hidden-state trap
Debugging inside the kernel
%pdb on # drop into the debugger at any uncaught exception
# after a crash, without %pdb:
%debug # inspect the traceback frame by frame
def parse(rows):
breakpoint() # Python 3.7+: enters pdb right here
return [r for r in rows if r["ok"]]
Debugging inside the kernel
(Pdb) l list source around the current line
(Pdb) p rows[0] print an expression
(Pdb) w show the call stack
(Pdb) u / d move up / down the stack
(Pdb) q quit the debugger and the cell
Detecting stale state
# list everything the kernel currently holds
%who DataFrame
%whos
# prove a variable was never defined by the code you can see
import inspect
print(inspect.getsource(parse))Full lesson: Debugging and the hidden-state trap →
Beyond local notebooks: Colab, Voila and Quarto
Voila: notebook as application
pip install voila
# hide code cells, show only widgets and outputs
voila dashboard.ipynb --no-browser --port 8866
Voila: notebook as application
# tag cells so Voila and nbconvert know what to hide
# View > Cell Toolbar > Tags, then add: hide-input
# or in a cell:
from IPython.display import display, Markdown
display(Markdown("# Sales dashboard"))
Quarto, and when to stop using notebooks
quarto render report.qmd --to html
quarto render report.qmd --to pdf
quarto preview report.qmdFull lesson: Beyond local notebooks: Colab, Voila and Quarto →
FAQ
Is this Jupyter Notebook cheat sheet free to use?
Where do the examples come from?
How do I go deeper than a cheat sheet?
Related cheat sheets
Python 3 NumPy pandas Matplotlib Flask FastAPI
Last refreshed 2026-09-27.