Notebooks, cells and execution order

Jupyter · Essentials · 10 min

Every notebook surprise, from 'NameError' to stale results, comes from how cells and execution order work.

A notebook (.ipynb file) is a sequence of cells. A code cell holds code that you run with Shift+Enter; its output (printed text, the value of the last expression, a chart, a table) appears right below it and is saved in the file. A Markdown cell holds formatted text, headings, lists, links and LaTeX math, so a notebook can read like a report.

Code runs in a separate process called the kernel (for Python, an IPython kernel). The kernel keeps one shared namespace for the whole notebook: a variable defined in one cell is visible in every other cell run afterwards.

The number in brackets, [5], shows the order in which cells were executed. This order, not the position on the page, determines the kernel's state. You can run cell 7 and then cell 2, edit cell 2 and rerun it, or delete a cell whose variable still lives in memory. The result is hidden state: the notebook on screen no longer explains the results.

Habits that avoid trouble:

  • Run cells top to bottom and keep the notebook runnable in that order.
  • Before sharing, use Restart Kernel and Run All Cells; if anything fails, the notebook was relying on hidden state.
  • Keep cells small and focused: load data, transform, plot.

Only the last expression of a cell is displayed automatically; use print() or display() for anything else.

Example

# Cell [1]
prices = [3.5, 4.0, 2.25]

# Cell [2]
total = sum(prices)
total                      # last expression is displayed: 9.75

# Cell [3] - later edited to: prices = [1, 2] and re-run
prices = [1, 2]

# Cell [2] is NOT re-run automatically, so `total` is stale:
print(total)               # 9.75, although sum(prices) is now 3
print(sum(prices))         # 3
# Fix: Kernel > Restart Kernel and Run All Cells

Remember

  • Cells share one kernel namespace; execution order defines state
  • Only the last expression of a cell is shown automatically
  • Restart and Run All before trusting or sharing results

Watch out for

  • Deleting a cell and assuming its variables are gone; they live in the kernel until restart.

Check yourself

  1. You ran cells in the order 1, 3, 2. What determines the values of variables now?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: jupyterlab.readthedocs.io/en/stable/user/notebook.html