Level 3 In-Depth AI · Programming and Tools
Notebooks: Jupyter and Colab
Notebooks let you run code a piece at a time and see results, tables and plots right under it. How cells and the kernel work, the hidden-state trap, magic commands, free GPUs on Colab, and when to move to plain scripts.
- Level
- ●●●●● Beginner
- Reading
- 10 min
- To learn it well
- 45 minutes to read, an hour to practise
- Builds on
- 1 concept →
- Quiz
- 5 questions ↓
Read first
Python for AIThis leads to
—The full path from zero — 1 concept before this one
- Python for AI
- Notebooks: Jupyter and Colab
Read them roughly in this order. See it on the concept map →
Why it matters
Most AI work starts with exploration. You load a dataset and look at it. You try a model, see the result, change one thing, and try again. Writing a whole program, running it from the top, and printing results to a terminal makes that loop slow.
A notebook is a document that mixes runnable code, its output and written notes. You run one small piece of code, see its result straight away, as a number, a table or a chart, and decide what to do next. Data scientists, researchers and students use notebooks for almost all exploratory work. Most courses in this guide's reading lists, including the book Dive into Deep Learning and the fast.ai course, are written as notebooks. Google Colab runs notebooks in your browser on Google's computers, with a free GPU, so you can train real neural networks without installing anything.
Notebooks also have a well-known trap, hidden state, that produces results nobody can reproduce. Understanding how notebooks work under the hood prevents it.
The intuition
Think of a notebook as a conversation with a calculator that has a memory. You type something, it answers, and it remembers what you told it. Later questions can use earlier answers.
The notebook has two parts that are easy to confuse:
- The page you see: a list of cells. A code cell holds some Python. A text cell (a "Markdown" cell) holds notes, headings and equations.
- The kernel: a separate running Python process that actually executes the code and holds all the variables in its memory.
When you run a cell, the page sends its code to the kernel. The kernel runs it, changes its memory, and sends any output back to be displayed under the cell. The kernel knows nothing about the page. It remembers only what it has been told, in the order it was told, which need not be the order the cells appear on the page.
Key idea The page is not the program. The kernel's memory is the real state, and it is built from every cell you ran, in the order you ran them, including cells you have since edited or deleted.
How it works
Cells and execution counts
Press Shift+Enter to run the current cell and move to the next. Next to each code cell is a number in brackets, such as [3]. It means "this was the third cell run since the kernel started". A [*] means it is still running. If you see cells numbered [7], [2], [5] from top to bottom, they were run out of order. That is a warning sign.
If the last line of a cell is an expression, the notebook shows its value automatically, nicely formatted. A Pandas and Working with Data table appears as a real table, and a Matplotlib chart appears as an image. You do not need print.
The kernel and its memory
Because the kernel keeps everything in memory, you can load a large dataset once, which might take a minute, and then experiment with it for an hour without reloading. That is the great strength of notebooks.
It is also the danger. Suppose you run these cells:
[1] threshold = 0.5
[2] big = x[x > threshold] # keep values above the threshold
len(big) # 499806
Then you go back, change the first cell to threshold = 0.9, and run only that cell. The page now says threshold = 0.9 above a cell whose output says 499,806, but that number was computed with 0.5. big still holds the old values, because the second cell has not been run again. Anyone reading the notebook, including you next week, will draw the wrong conclusion. This mismatch between what the page shows and what is in memory is called hidden state.
The cure is simple: Kernel → Restart Kernel and Run All Cells in JupyterLab (in Colab, Runtime → Restart session and run all). This throws away the kernel's memory and runs every cell from top to bottom. If the notebook still works and gives the same answers, it is trustworthy. Do this before you share a notebook or believe a result.
Magic commands
Lines starting with % or ! are not Python. They are instructions to the notebook system itself, called magic commands. A single % applies to one line. A double %% at the top of a cell applies to the whole cell. The ones you will use most:
| Command | What it does |
|---|---|
%timeit expr |
Runs expr many times and reports the average time. Ideal for comparing two ways of doing something. |
%%time |
Times the whole cell once. |
%pip install pandas |
Installs a package into the kernel's own environment. Safer than !pip, which may use a different Python. |
!nvidia-smi |
! runs a shell command. This one shows the GPU, its memory use and the driver version. |
!ls, !wget URL |
List files, download a file. |
%load_ext autoreload then %autoreload 2 |
Automatically reloads your own .py files when you edit them, so you can keep code in files but test it in a notebook. |
%%writefile train.py |
Saves the cell's contents to a file. |
%debug |
After an error, opens a debugger at the line where it happened, so you can inspect variables. |
Google Colab
Colab is Google's hosted version of Jupyter. You open colab.research.google.com, sign in with a Google account and start a notebook. Google gives you a temporary virtual machine, called a runtime, with Python and the main AI libraries (NumPy, pandas, scikit-learn, PyTorch, Transformers) already installed.
- To get a GPU: Runtime → Change runtime type → choose a GPU. On the free tier this is usually an NVIDIA T4 with 16 GB of memory, subject to availability (as of late 2026).
- Everything is temporary. When the runtime disconnects, after a period of inactivity or at a maximum session length of up to about 12 hours on the free tier, its memory and any files you saved to its disk are gone. The notebook itself is saved in your Google Drive, so your code survives, but you must rerun it to rebuild the variables.
- To keep files, mount your Google Drive:
from google.colab import drive
drive.mount("/content/drive") # asks for permission, then your Drive appears as a folder
Save model checkpoints and results under /content/drive/MyDrive/. Kaggle Notebooks work much the same way, with a weekly GPU quota and easy access to Kaggle's public datasets. Setting Up Your Environment compares the options.
Running Jupyter on your own computer
Install it into your project's virtual environment with pip install jupyterlab (or uv add jupyterlab) and start it with jupyter lab. It opens in your browser, but everything runs locally. Alternatively, VS Code opens .ipynb files directly. Either way, make sure the notebook's kernel is the Python from your project's environment, or your packages will be "missing".
In code
Here are cells you can paste into a Colab or Jupyter notebook one at a time. They show the kernel's memory at work and use %timeit to measure something you will meet again in NumPy and Array Thinking: Python loops are slow, and NumPy operations are fast.
# Cell 1: load once, use many times
import numpy as np
rng = np.random.default_rng(0)
x = rng.random(1_000_000) # a million random numbers in [0, 1)
x.shape, x[:3].round(3)
# ((1000000,), array([0.637, 0.27 , 0.041]))
# Cell 2: a plain Python loop versus NumPy
def py_sum(values):
total = 0.0
for v in values:
total += v
return total
%timeit py_sum(x)
%timeit x.sum()
# 60.1 ms ± 3.15 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 190 μs ± 1.02 μs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
# Cell 3: what hardware am I on? (in Colab with a GPU runtime)
!nvidia-smi
import torch
torch.cuda.is_available() # True on a GPU runtime, False otherwise
On a laptop the NumPy sum was over 300 times faster than the loop. Your timings will differ, but the gap will be similar. The x from cell 1 was still in the kernel's memory when cell 2 ran, so the data was created only once.
Common pitfalls
- Out-of-order execution. Execution counts that jump around mean the page may not match memory. Restart and run all.
- Deleted but not forgotten. Deleting a cell does not delete the variables it created. Code that uses them keeps working until you restart, then fails.
- "ModuleNotFoundError" in a notebook but not in the terminal. The kernel is a different Python. Use
%pip installinside the notebook, or choose the right kernel. - Memory filling up. Every large array or model you create stays in memory until you delete it (
del big) or restart the kernel. On a GPU this shows up asCUDA out of memory. Restarting frees everything. - Losing work on Colab. Files written to the runtime's disk vanish when it disconnects. Save to Google Drive and keep checkpoints as training runs.
- Huge outputs. Printing a million-row table or the loss at every step makes the notebook file enormous and slow. Print every hundredth step, or plot instead.
Watch out A notebook whose cells were run out of order can show results that cannot be reproduced. Before you trust a number, publish a chart or send the notebook to anyone, run Restart & Run All and check that you get the same answer.
When to move to scripts
Notebooks are excellent for exploring, teaching and presenting. They are poor for code that must run reliably again and again. Move to plain .py files when:
- you copy the same function into a third notebook (put it in a module and import it);
- training takes hours and should run unattended, perhaps on a rented GPU (run
python train.pyin the terminal, ideally insidetmuxornohupso it survives a disconnect); - several people edit the code (notebooks are JSON files full of outputs, and their changes are hard to compare and merge in git);
- you need tests or a deployed service.
A common, healthy pattern is to keep reusable code in .py files, import it into a notebook with %autoreload on, and use the notebook only for experiments and charts.
A bit of history
The notebook idea is older than Jupyter. Mathematica introduced notebooks in 1988. IPython, an improved interactive Python shell, was started in 2001 by Fernando Pérez, then a graduate student. It gained a browser-based notebook in 2011. In 2014 the language-independent parts were split out as Project Jupyter, named after three of its first languages, Julia, Python and R, and also a nod to Galileo's notebooks recording the moons of Jupiter. JupyterLab, the more complete interface, followed around 2018. Google opened Colab to the public around 2017, and its free GPUs made it the default place for many people to train their first neural network.
Try it
- Open Colab, paste in cells 1 and 2 from "In code" and run them. How much faster is NumPy on Google's machine?
- Reproduce the hidden-state trap: set
threshold = 0.5, computelen(x[x > threshold])in a second cell, then change only the first cell to0.9and rerun it. Notice that the second cell's output is now wrong. Fix it with Restart and run all.- Switch the Colab runtime to a GPU and run
!nvidia-smi. Which GPU did you get, and how much memory does it have?Hint for 1: the speed-up depends on the CPU, but expect a factor of 100 or more.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Google Colab
Free Jupyter notebooks in the browser, with GPUs. Nothing to install.
Project Jupyter documentation
Official documentation for Jupyter notebooks, JupyterLab and kernels, including installation and how the pieces fit together.
Python Data Science Handbook
Free online book covering IPython and notebooks, NumPy, pandas, Matplotlib and scikit-learn, every chapter a runnable notebook.
Colab FAQ
Official answers on Colab's free resources, usage limits, GPUs and how runtimes time out.
IPython built-in magic commands
Reference for every % and %% magic command available in Jupyter notebooks, such as %timeit, %debug and %autoreload.
Kaggle Notebooks documentation
How Kaggle's free browser notebooks work, including GPU and TPU quotas and attaching datasets.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/programming/jupyter-and-colab.md