Faking the execution count (the number in square brackets like [1], [2], etc.) in a Jupyter Notebook is generally not recommended, as it can mislead others who view or use your notebook. However, if you have a legitimate reason—such as restoring a notebook's state or testing—here are a few approaches:
Jupyter Notebooks are stored as .ipynb files, which are JSON files. You can manually edit the execution count by:
.ipynb file in a text editor (e.g., VS Code, Notepad++)."execution_count" in the JSON.null to 1).Example:
json"cells": [ { "cell_type": "code", "execution_count": 1, // Change this value "metadata": {}, "outputs": [], "source": ["print('Hello, world!')"] } ]
nbformat Library (Programmatic Approach)You can use Python's nbformat library to programmatically update execution counts:
pythonimport nbformat # Load the notebook with open("your_notebook.ipynb", "r", encoding="utf-8") as f: nb = nbformat.read(f, as_version=4) # Update execution counts for cell in nb.cells: if cell.cell_type == "code": cell.execution_count = 1 # Set to desired value # Save the notebook with open("your_notebook.ipynb", "w", encoding="utf-8") as f: nbformat.write(nb, f)
Some Jupyter extensions (e.g., Collapsible Headings) allow you to manipulate notebook metadata, but they don’t directly support faking execution counts. You’d still need to edit the JSON or use nbformat.
If you want to reset execution counts to 1, 2, 3, ...:
Kernel > Restart).Cell > Run All).