Jupyter Notebooks & JupyterLab
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
A Jupyter notebook is a document that mixes code, its output, charts and prose, and it is the default medium for exploratory data analysis in Python. It is also the source of the most common reproducibility problems in data science, because it lets you run code in any order and keeps the results on screen long after the code that made them has changed. This page explains what a notebook actually is, how to run one with the environments set up in Setting Up a Data Science Environment, and the habits that keep notebooks trustworthy. Examples target Python 3.13 or 3.14 and were run on Python 3.13. The page targets JupyterLab 4.6 and Notebook 7.6, together with NumPy 2.5, pandas 3.1 and scikit-learn 1.9; everything was checked in October 2026. Code cells shown below are ordinary Python and were executed as scripts with those versions.
Architecture: browser, server and kernel
Three separate pieces cooperate, and knowing which one is misbehaving is half of troubleshooting:
-
The front end (JupyterLab, Jupyter Notebook 7, VS Code, PyCharm and others) edits cells and shows output. It runs in the browser or in an editor and never executes your code.
-
The server serves files, starts and stops kernels, and relays messages. It listens on a local port, by default 8888, and protects access with a token.
-
The kernel is a separate process that executes the code and holds all variables in memory. For Python the kernel is
ipykernel, which is IPython running behind the messaging protocol. Other languages (R, Julia, SQL) have their own kernels.
The kernel, not the server, decides which packages are importable. The server can run in one environment and the kernel in another, and this separation is why a notebook can fail to import a package that the terminal sees. Stopping the server does not delete anything, but restarting the kernel clears every variable.
The notebook file format
A notebook is a JSON document with the extension .ipynb. It holds a list of cells and, for each code cell, the
outputs saved the last time it ran, including images as base64 text. A minimal example:
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": ["# Churn analysis"]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{"name": "stdout", "output_type": "stream", "text": ["3\n"]}
],
"source": ["print(1 + 2)"]
}
],
"metadata": {
"kernelspec": {"display_name": "Python 3", "language": "python", "name": "python3"},
"language_info": {"name": "python"}
},
"nbformat": 4,
"nbformat_minor": 5
}
Three consequences follow. Outputs live inside the file, so a notebook full of charts is large and its Git diffs are
unreadable. The execution_count numbers record the order in which cells were last run, which is the first clue that a
notebook was run out of order. And everything in the file, including output text, is shared when you share the file, so
never leave secrets, personal data or file paths with usernames in the output of a notebook that you commit or send.
Jupyter Notebook, JupyterLab and the rest
-
JupyterLab is the main interface: multiple notebooks and files in tabs, a file browser, terminals, a text editor and extensions. JupyterLab 4.6 is current.
-
Jupyter Notebook 7 is the simpler single-document interface. Since version 7 it is built from JupyterLab components, so the two share extensions and the same notebook format. The older "classic" interface is no longer developed.
-
Editors (VS Code, PyCharm and others) open
.ipynbfiles with their own interface, and use the same kernels. See Python IDEs and Tools for the Python side. -
Hosted services run the same software for you, with the trade-off that your data goes to someone else’s machine.
Installing and starting
# inside an activated environment
python -m pip install jupyterlab
jupyter lab
Source: JupyterLab installation.
With conda, conda install jupyterlab from conda-forge does the same. The command prints a URL with a token and opens
a browser. To start in a particular folder or on a particular port, use jupyter lab --notebook-dir=data --port=8890.
Stop the server with Ctrl+C in the terminal, confirming when asked.
Jupyter with uv
uv does not need Jupyter to be installed in the project. This starts JupyterLab with the project’s environment:
uv run --with jupyter jupyter lab
To make the project’s own environment available as a named kernel, add ipykernel as a development dependency and
register it:
uv add --dev ipykernel
uv run ipython kernel install --user --env VIRTUAL_ENV $(pwd)/.venv --name=project
uv run --with jupyter jupyter lab
Then choose the kernel project in the notebook’s kernel picker. Source: Using uv with Jupyter (uv documentation).
The same guide documents how installing from inside a notebook interacts with uv. In a notebook that uses the project
kernel, !uv add pydantic adds the package to pyproject.toml and uv.lock, and !uv pip install pydantic installs it
into the project environment without recording it. %pip install has the same limitation as the second form: it
installs into the environment but nothing is written to the lock file, so the notebook works for you today and fails for
a colleague tomorrow. In a notebook that people will reuse, install with uv add or in the terminal, and never rely on
an unrecorded install.
Kernels with pip and conda
python -m pip install ipykernel
python -m ipykernel install --user --name churn --display-name "Python (churn)"
jupyter kernelspec list
jupyter kernelspec remove churn
Source: Installing the IPython kernel (IPython documentation).
Within a running notebook, import sys; sys.executable shows which interpreter the kernel uses, and
%pip list or !python -m pip list shows its packages. If you see the wrong path, you are connected to the wrong
kernel, not to a broken installation.
Working in a notebook
Cells, execution and the kernel
Cells are either code or Markdown (and raw). Run the current cell with Shift+Enter. Every code cell shares one namespace, held by the kernel, so a variable defined in a cell exists until it is overwritten, deleted, or the kernel restarts. The last expression of a cell is displayed automatically:
import numpy as np
import pandas as pd
rng = np.random.default_rng(42)
df = pd.DataFrame({"x": rng.normal(size=1000)})
df["y"] = 2 * df["x"] + rng.normal(scale=0.1, size=1000)
df.corr().round(3) # the last expression is shown as a table
Source: IPython tutorial. In a notebook the result appears below the cell; run as a script it prints:
x y x 1.000 0.999 y 0.999 1.000
(This is the output on the pinned versions; the exact decimals depend on the generator.) Note the explicit seed: a notebook without one produces a different table on every run.
Magics and shell commands
IPython adds two kinds of syntax that are not Python and therefore only work in IPython-based kernels. Line magics
start with % and affect one line, cell magics start with %% and affect the entire cell. A line starting with !
runs a shell command.
| Command | Purpose |
|---|---|
|
Times an expression, repeating it to get a stable figure. |
|
Times a whole cell. |
|
Shows Matplotlib figures below the cell. It is the default in current kernels. |
|
Re-imports modified modules automatically, so you can develop a function in a |
|
Lists the variables defined in the kernel. |
|
Runs a script in the notebook’s namespace. |
|
Opens a post-mortem debugger on the last exception. |
|
Runs a shell command; the output can be assigned to a variable. |
Source: IPython built-in magic commands. Because magics are not
Python, a cell that uses them cannot be pasted into a script, and Jupytext and nbconvert translate them as comments or
get_ipython() calls.
Rich display
Pandas objects, Matplotlib figures, images, HTML and LaTeX display richly. Use display() to show several objects from
one cell and pd.set_option to control table size:
import pandas as pd
from IPython.display import display
pd.set_option("display.max_rows", 20)
pd.set_option("display.precision", 3)
display(df.head(), df.describe())
Source: IPython.display.
Interactive widgets (ipywidgets) and interactive plotting libraries add controls and hover tooltips; they need the
front end extensions installed, which pip and conda do automatically in current versions.
The central problem: hidden state
Because cells can be run in any order, the notebook you see on screen can describe a state that no top-to-bottom run
would produce. A typical sequence: define df, run a cell that drops a column, edit the cell that dropped it to do
something else and run it again, never rerunning the earlier steps. The numbers on screen now depend on the history of
button clicks, not on the code. Deleted cells leave their variables alive in the kernel; renamed variables leave the
old ones behind; a cell that fails halfway has already modified the data.
Research on public notebooks confirms that this is not a rare edge case. Pimentel and colleagues (MSR 2019) took a large set of notebooks from GitHub and tried to re-execute them: only a minority ran to the end without errors, and a smaller share reproduced the results stored in the file. The commonest causes were missing dependencies, files that were no longer available, and out-of-order execution. Rule and colleagues (PLOS Computational Biology, 2019) distilled ten rules for notebooks that address the same problems. The rules that matter most:
-
Restart and run all before you share, commit or report a result. Make it a habit, and do it more often than feels necessary.
-
Seed every random generator with an explicit value (
np.random.default_rng(42),random_state=42in scikit-learn). -
Move code into functions and modules once it is stable, import them into the notebook, and test them with pytest. A notebook then calls the analysis instead of containing it.
-
Declare the environment (lock file or
environment.yml, see Setting Up a Data Science Environment) and show versions in the first cell. -
Keep data paths relative and the data separate from the notebook.
-
Tell a story: one question per notebook, headings, and conclusions in Markdown, with the heavy lifting elsewhere.
Version control
Outputs make .ipynb files a poor fit for Git: a rerun changes the execution counts and image bytes, and diffs show
JSON noise. Two complementary tools solve this.
nbstripout: commit without outputs
nbstripout removes outputs and execution counts when a notebook is staged, as a Git filter:
python -m pip install nbstripout
nbstripout --install # configures a Git filter for this repository
nbstripout notebook.ipynb # strip one file by hand
Source: nbstripout. After this, the file in the repository has no outputs and your working copy still does. Strip outputs by default, except for notebooks deliberately committed as rendered reports.
Jupytext: notebooks as plain text
Jupytext pairs a notebook with a script in the "percent" format, where each # %% line starts a cell, so the script is
what you review and diff:
python -m pip install jupytext
jupytext --set-formats ipynb,py:percent notebook.ipynb # pair the two files
jupytext --sync notebook.ipynb # update whichever side is older
# %% [markdown]
# # Churn analysis
# %%
import pandas as pd
df = pd.read_csv("people.csv")
df.head()
Source: Jupytext documentation. Commit the .py file as the source of truth
and keep the .ipynb out of version control or committed without outputs.
Running notebooks as programs
A notebook can be executed without opening a browser, which is how reports are produced on a schedule or in CI.
# execute and convert to HTML
jupyter nbconvert --to html --execute notebook.ipynb
# execute in place, failing if any cell raises
jupyter nbconvert --to notebook --execute --inplace notebook.ipynb
Source: nbconvert documentation. papermill adds parameters: mark one cell with the
tag parameters that defines default values, and override them from the command line, producing a new executed notebook
for each run:
python -m pip install papermill
papermill report.ipynb out-2026-10.ipynb -p month 2026-10 -p threshold 0.8
Source: papermill documentation. Both tools run the notebook from first cell to last in a fresh kernel, which is exactly the property that restart-and-run-all tests. A nightly job that executes important notebooks is the most effective protection against rotting notebooks.
Alternatives and companions
-
Quarto renders
.qmdfiles or notebooks to HTML, PDF, slides and websites, executing code with the Jupyter kernels (and with R). See Quarto; the R-side equivalent in this site is Reports with Quarto and R Markdown. -
marimo is a reactive notebook stored as a plain Python file. It tracks dependencies between cells, so changing a cell re-runs the cells that depend on it and removes the hidden-state problem by design. See marimo; the trade-off is a different file format and fewer integrations than Jupyter.
-
Scripts and modules remain the right place for anything that runs in production. A common division is exploration in a notebook, then moving the useful logic into a package or script. For the R equivalent of exploring with a console and scripts, see IDEs and the R Console.
-
Python from R: Python Interoperability with reticulate.
Security notes
A running Jupyter server executes arbitrary code with your permissions. Do not expose it to a network without authentication and TLS, do not disable the token, and do not open notebooks from untrusted sources in a trusted session: a notebook can contain HTML and JavaScript outputs, and Jupyter marks notebooks as untrusted until you run them yourself. Never put credentials in a cell; read them from environment variables or a secrets manager.
A practical notebook template
# --- Cell 1: parameters and versions ------------------------------------------
import sys
from importlib.metadata import version
SEED = 42
DATA = "data/people.csv"
print(sys.version.split()[0], {p: version(p) for p in ("numpy", "pandas", "scikit-learn")})
# --- Cell 2: imports and configuration ----------------------------------------
import numpy as np
import pandas as pd
rng = np.random.default_rng(SEED)
pd.set_option("display.max_columns", 30)
# --- Cell 3: load, then one question per section ------------------------------
df = pd.read_csv(DATA)
df.shape
Source: IPython documentation. Data loading is covered in Data Sources & File Formats; the next analysis steps are in Data Cleaning & Preparation and Exploratory Data Analysis.
Where older tutorials are outdated
| Older statement | Current practice (October 2026) |
|---|---|
"Start |
Notebook 7 and JupyterLab share one code base; JupyterLab is the main interface. |
"Use |
It is the default in current kernels; call it only to switch backends. |
"Install packages with |
Acceptable for experiments, but nothing is recorded: with uv use |
"Save the notebook with outputs; they document the results." |
Outputs hide state and bloat repositories. Strip them or pair the notebook with a script, and regenerate outputs by running it. |
"A notebook is a good deliverable." |
It is a good exploration and reporting tool; deliver logic as tested modules and reports as rendered output. |