Jupyter Notebook Shortcuts And Magic Commands Refe
You’re in the zone. You’ve just spotted an outlier in your data, and you know exactly what cell to write next. Your hand leaves the keyboard, reaches for the mouse, clicks the tiny “+” button, moves back to the keyboard, and… the thought is gone. The real bottleneck in exploratory data science isn’t your CPU or your code—it’s the friction between your brain and the interface. Every mouse click is a micro-interruption that breaks your flow.
This article isn’t a dry reference list of every shortcut in Jupyter. It’s a workflow upgrade. By the time you finish, you’ll navigate a notebook without touching the mouse, and you’ll be using “magic commands” that feel like cheat codes. But before any of that makes sense, you need to understand the one mental model that unlocks everything: the two-mode system.
The Two Modes That Change Everything
Think of Jupyter like a video game where you switch between “explore” and “fight” modes. In explore mode, you walk around and interact with the world. In fight mode, your buttons do completely different things—they swing swords instead of opening doors. Jupyter works the same way. It has two modes, and every keyboard shortcut depends on which mode you’re in.
Edit mode is when you’re inside a cell, typing code or markdown. The cell has a green border. In this mode, your keyboard does exactly what you’d expect: letters type letters, Enter adds a new line, and Tab indents. You enter edit mode by pressing Enter on a selected cell. You can also enter it by clicking into the cell.
Command mode is when you’re operating on the notebook structure itself—adding cells, deleting them, changing their type, or navigating between them. The selected cell has a grey border with a blue left margin. In this mode, your keyboard becomes a set of structural commands. Pressing “A” doesn’t type the letter A; it inserts a new cell above. You enter command mode by pressing Esc.
This is the hardest part for new users to internalize. You can’t run cell-level shortcuts while you’re typing, and you can’t type while you’re in command mode. If you’ve ever accidentally typed “dd” into a cell and wondered why it disappeared, you were in command mode without realizing it.
Here’s a quick cheat sheet for the mode-switching itself:
| If you want to… | Make sure you’re in… | Then press… |
|---|---|---|
| Start typing in a cell | Command mode | Enter |
| Stop typing and navigate | Edit mode | Esc |
| See all available shortcuts | Command mode | H |
The last row is your built-in lifeline. Press H in command mode, and Jupyter pops up a window with every shortcut available. You don’t need to memorize this article—you just need to remember that H exists.
JupyterLab discovery: The classic Jupyter Notebook (what you get with
pip install notebookor Notebook 6/7) uses the H key for this. JupyterLab uses a different discovery path—the Command Palette, which you open with Ctrl+Shift+C (or Cmd+Shift+C on Mac). We’ll cover JupyterLab differences in detail later. For now, if H doesn’t work, you’re probably in JupyterLab.
Essential Command-Mode Shortcuts (Classic Notebook)
These are the shortcuts that actually save time every day—not the full list of 50+, but the 10–12 that cover 80% of your navigation. They’re grouped by what you’re trying to do. All of these assume you’re in command mode (press Esc first if you’re not sure).
Cell Creation
| Action | Shortcut | What It Actually Means |
|---|---|---|
| Insert cell above | A | “Above”—creates a new cell right where your cursor would naturally go next if you’re building downward. |
| Insert cell below | B | “Below”—the one you’ll use most when writing new code in sequence. |
Cell Type Switching
| Action | Shortcut | What It Actually Means |
|---|---|---|
| Change to code cell | Y | “Y” for “code” (no, it doesn’t stand for anything—it’s just near the other type keys). |
| Change to markdown cell | M | “M” for “Markdown.” Use this to write explanations, not code. |
| Change to raw cell | R | “R” for “Raw”—content that won’t be executed or rendered. Rarely used day-to-day. |
Execution
| Action | Shortcut | What It Actually Means |
|---|---|---|
| Run cell and move down | Shift+Enter | The workhorse. Executes the current cell and selects the next one. If there’s no cell below, it creates one. |
| Run cell in place | Ctrl+Enter | Executes but keeps you on the same cell. Useful when you’re tweaking parameters and want to see the output without moving. |
| Run cell and insert below | Alt+Enter | Executes and always creates a new cell below, even if one already exists. Great for exploratory “what if?” branches. |
Deletion and Undo
| Action | Shortcut | What It Actually Means |
|---|---|---|
| Delete selected cell(s) | D, D | Press D twice, quickly. This is the hardest-to-discover but most satisfying shortcut. It feels like a tiny drumroll before the cell vanishes. |
| Undo cell deletion | Z | The one that saves you when you accidentally D,D the wrong cell. Think: “Z for undo, like Ctrl+Z, but in command mode.” |
Navigation and Selection
| Action | Shortcut | What It Actually Means |
|---|---|---|
| Move up/down one cell | ↑ / ↓ (or K / J) | Arrow keys work, but K and J keep your hands on the home row. |
| Multi-select cells | Shift+↑ / Shift+↓ | Selects a range of cells so you can delete, copy, or move them as a group. |
| Select all cells | Ctrl+A | Selects every cell in the notebook. |
These are Classic Jupyter Notebook defaults (what you get with
nbclassicor Notebook 6/7). If you’re in JupyterLab, some of these differ—we’ll cover that next. And yes, all of these are customizable. If you want to remap D,D to something else, you can do it through Settings → Advanced Settings Editor → Keyboard Shortcuts.
JupyterLab Shortcuts: What’s Different
You followed a tutorial. You pressed A in command mode, expecting a new cell above. Nothing happened. You’re not crazy—you’re just in JupyterLab, and it has its own default keybindings.
JupyterLab is the next-generation interface that’s gradually replacing the classic Notebook. It looks more like an IDE, with tabs, a file browser, and a more flexible layout. But its shortcut philosophy is different in a few key ways that trip people up.
First, JupyterLab doesn’t use the H key to show shortcuts. Instead, it has a Command Palette—a searchable list of every possible action. Open it with Ctrl+Shift+C (Windows/Linux) or Cmd+Shift+C (Mac). Start typing what you want to do (“insert cell,” “restart kernel”), and it’ll show you the matching commands and their shortcuts. This is actually more powerful than the classic H cheat sheet once you get used to it, because you can search by what you want to accomplish rather than hunting through a static list.
Here’s a comparison of the shortcuts that differ most between the two environments:
| Action | Classic Notebook | JupyterLab (4.x default) |
|---|---|---|
| Show shortcuts | H (command mode) | Ctrl+Shift+C (Command Palette) |
| Insert cell above | A | A (usually the same, but may be Ctrl+Shift+A in some versions) |
| Insert cell below | B | B (usually the same, but may be Ctrl+Shift+B in some versions) |
| Delete cell | D, D | D, D (same) |
| Run cell, move down | Shift+Enter | Shift+Enter (same) |
| Markdown bold | Doesn’t work in markdown cells by default | Ctrl+B / Cmd+B works in markdown cells |
| Customize shortcuts | Settings → Keyboard Shortcuts | Settings → Advanced Settings Editor → Keyboard Shortcuts |
Version-pinning caveat: JupyterLab 4.x defaults are shown here. Shortcuts can change between major versions. If something doesn’t work, open the Command Palette and search for the action—it’ll show you the current binding. And if you’re using the VS Code Jupyter extension, it has its own entirely separate shortcut set. That’s a different article entirely, but don’t blame yourself if nothing matches—you’re in a different ecosystem.
To view and customize your shortcuts in JupyterLab, go to Settings → Advanced Settings Editor → Keyboard Shortcuts. You’ll see a JSON-like editor where you can remap any command. We’ll use this later to build a custom workflow.
What Are Magic Commands? (And Why They’re Not Just “Special Functions”)
You’ve probably typed %matplotlib inline a hundred times without thinking about what the % actually means. It’s not Python. If you tried to run it in a plain .py file, you’d get a syntax error. Magic commands are Jupyter’s way of letting you talk directly to the kernel and the notebook environment—they’re meta-Python.
Think of it this way: normal Python code tells the interpreter what to compute. Magic commands tell the notebook how to compute it, or what to show you about the computation. They control the environment around your code.
There are two flavors:
- Line magics start with a single
%and apply to one line. Example:%timeit sum(range(1000))times that one line. - Cell magics start with
%%and apply to the entire cell below them. Example:%%timeitfollowed by multi-line code times the whole block.
This is the hardest part to internalize: the %% cell magic must be on the first line of the cell, and the rest of the cell becomes its input. You can’t put a comment above it, and you can’t have two cell magics in one cell.
Let’s see what magics are even available. The built-in discovery tool is %lsmagic:
%lsmagic
This prints a list of every available line magic and cell magic. The output is long, but it’s your menu. When you spot one you’re curious about, you can pull up its documentation with a question mark:
%timeit?
This prints the full docstring for %timeit—what it does, what parameters it accepts, and examples of how to use it. You don’t need to memorize every magic command. You just need to remember %lsmagic to see what’s available, and %magic_name? to learn how to use it.
The Magic Commands You’ll Actually Use Every Day
Here are the 8–10 magic commands that earn their keep in daily data science work, grouped by what they help you do. Each one gets a concrete example and a plain-English interpretation of the output.
Timing: %timeit and %time
When you want to know if your code is slow, you need to measure it. But measuring a single run is misleading—your computer might be busy with something else at that exact millisecond. %timeit solves this by running your code multiple times and giving you a statistically meaningful average.
%timeit sum(range(1000))
The output might look like: 7.81 µs ± 45.7 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each). In plain English: “This operation takes about 7.8 microseconds, and across many runs, the variation is tiny—only about 46 nanoseconds of jitter. I’m confident in this number because I ran it 100,000 times per trial, across 7 separate trials.”
%time is the simpler cousin. It runs the code exactly once and reports the wall-clock time:
%time sum(range(1000))
The output: CPU times: user 16 µs, sys: 0 ns, total: 16 µs and Wall time: 19.9 µs. In plain English: “This took 20 microseconds of real-world time. The CPU spent 16 microseconds actually computing, and the rest was overhead.”
When should you use which? Use %timeit when you’re micro-benchmarking and need a reliable number. Use %time when you’re running something that takes seconds or minutes and you just want to know how long it took—or when the code has side effects (like writing a file) that you don’t want repeated 100,000 times.
For multi-line timing, use the cell-magic version:
%%timeit
result = []
for i in range(1000):
result.append(i ** 2)
This times the entire cell as one block. The output interpretation is the same: mean time, standard deviation, and how many runs were used to compute it.
Debugging: %pdb
This is the one that saves you from endless print() statements. When you run %pdb, you’re telling Jupyter: “If any code in this notebook raises an error, automatically drop me into the Python debugger at the exact line where it failed.”
%pdb
The output is simply Automatic pdb calling has been turned ON. Now let’s see what happens when we trigger an error:
def divide(a, b):
return a / b
divide(10, 0)
Instead of just printing a traceback and stopping, Jupyter drops you into an interactive pdb prompt right at the return a / b line. You can type a to see the value of a, b to see b, type(b) to check its type, and continue to let the error propagate. In plain English: “I’ve frozen time at the moment of the crash. Inspect everything. Figure out what went wrong.”
To turn it off, just run %pdb again—it toggles.
Environment: %who and %whos
After an hour of exploration, your notebook’s namespace is cluttered with variables. %who tells you what’s in scope:
%who
This prints a simple list of variable names. %whos goes further—it shows each variable’s type and a preview of its contents:
%whos
The output is a table: Variable | Type | Data/Info. In plain English: “Here’s everything you’ve created so far, what type it is, and a quick peek at what it holds.” This is invaluable when you’ve lost track of whether df is your raw data or your cleaned data.
You can also filter by type:
%whos DataFrame
This shows only your DataFrames. In plain English: “Show me just the tables I’ve made—ignore the lists, strings, and models.”
File Operations: %pwd, %cd, and %%writefile
Your notebook has a working directory, and it’s often not what you think it is. %pwd prints it:
%pwd
The output is a path like /home/user/projects/analysis. In plain English: “Any relative file path you use—like pd.read_csv('data.csv')—will be resolved starting from this folder.”
%cd changes that directory:
%cd /home/user/projects/data
In plain English: “From now on, ./ means this new folder.” This is especially useful when your notebooks and data live in different directory trees.
%%writefile takes the entire contents of a cell and writes them to a file:
%%writefile config.yaml
database:
host: localhost
port: 5432
The output: Writing config.yaml. In plain English: “I’ve taken everything in this cell and saved it as a real file on disk.” This is great for creating small configuration files, scripts, or even Python modules directly from your notebook.
Plotting: %matplotlib inline and %matplotlib notebook
You already know %matplotlib inline—it’s the one that makes plots appear as static images below your cells:
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.random.randn(100).cumsum())
The plot appears, but you can’t zoom, pan, or interact with it. That’s where %matplotlib notebook comes in:
%matplotlib notebook
import matplotlib.pyplot as plt
import numpy as np
plt.plot(np.random.randn(100).cumsum())
This gives you an interactive plot—you can zoom with the toolbar, pan around, and see exact coordinates on hover. In plain English: “Instead of a dead image, here’s a living plot you can explore.” The tradeoff is that interactive plots use more browser resources and can slow down if you have many of them.
Running Scripts: %run
Sometimes your logic lives in a .py file, but you want to execute it in the notebook’s namespace so you can inspect the results. %run does exactly that:
%run my_script.py
This executes my_script.py as if you’d typed its contents directly into a cell. Any variables it creates are now available in your notebook. In plain English: “Take that standalone script and run it right here, sharing all its variables with me.”
History: %history
You’ve executed 47 cells, and you need to remember exactly what sequence of commands produced that result. %history shows you everything you’ve run:
%history
This prints a numbered list of every input you’ve executed in this session. You can filter it:
%history 10 20 # Show inputs 10 through 20
%history -g df # Show every input that contains the string 'df'
In plain English: “Show me what I’ve done, so I can reconstruct my workflow or copy it into a script.”
The %autoreload Trap (And How to Get It Right)
Here’s a story you’ve probably lived: You’re writing a helper function in utils.py. You import it into your notebook. You find a bug. You edit utils.py and save it. You re-run the import cell in your notebook. Nothing changes. The old version is still running. You restart the kernel. It works. But now you’ve lost all your variables, and you’re frustrated.
What’s actually going on here? Python’s import system caches modules. When you write from utils import my_function, Python loads utils.py, compiles it, and stores the result in sys.modules. The next time you import it—even in a different cell—Python says, “I already have utils in my cache, no need to re-read the file.” Your edits to utils.py are invisible until you force Python to reload.
The solution is %autoreload, but it requires a two-step setup:
%load_ext autoreload
%autoreload 2
Step 1: %load_ext autoreload loads the autoreload extension. This is like installing a plugin—it makes the %autoreload command available.
Step 2: %autoreload 2 enables full auto-reloading. Mode 2 means “reload every imported module before executing any cell.” There are three modes:
- 0 (or “off”): No auto-reloading. This is the default.
- 1 (or “explicit”): Only reload modules you’ve specifically marked with
%aimport module_name. - 2 (or “all”): Reload every imported module, every time. This is what most people want.
Note that %load_ext autoreload must be run in every new kernel session. It’s not persistent across restarts. If you restart your kernel, you need to re-run that two-line setup before your auto-reloading works again.
The pro tip: add these lines to your IPython startup profile so they run automatically in every notebook. Create or edit ~/.ipython/profile_default/ipython_config.py and add:
c.InteractiveShellApp.extensions = ['autoreload']
c.InteractiveShellApp.exec_lines = ['%autoreload 2']
Now every notebook you open will have autoreload enabled from the start. No more kernel restarts, no more confusion.
Let’s demonstrate that it works. First, we’ll create a tiny module on disk:
%%writefile my_utils.py
def greet():
return "Hello, version 1!"
Now import and use it:
from my_utils import greet
print(greet())
Output: Hello, version 1!
Now—without restarting the kernel—edit the file. We’ll overwrite it with a new version:
%%writefile my_utils.py
def greet():
return "Hello, version 2!"
If you don’t have autoreload enabled, re-running the import cell would still print “Hello, version 1!” But with %autoreload 2 active, just re-run the cell that calls greet()—no need to re-import:
print(greet())
Output: Hello, version 2! In plain English: “I noticed my_utils.py changed on disk, so I reloaded it automatically. Your function now uses the latest code, and you didn’t lose any of your other variables.”
Building Your Own Shortcut Workflow
Knowing the shortcuts in isolation is one thing. Weaving them into a smooth, mouse-free rhythm is another. Let’s walk through a typical exploratory data analysis session and see how the pieces fit together.
Scenario: You’ve just downloaded a new CSV and you want to understand what’s in it, clean it up, and save a processed version.
You open a fresh notebook. Your hands are on the keyboard.
Step 1: Create your first cell and import libraries. You’re in command mode (grey border, blue margin—press Esc if you’re not sure). Press B to create a cell below. Press Enter to enter edit mode (green border). Type your imports:
import pandas as pd
import numpy as np
Press Shift+Enter to run and move down. A new cell appears below automatically.
Step 2: Load the data. You’re already in edit mode in the new cell. Type:
df = pd.read_csv('sales_data.csv')
df.head()
Press Shift+Enter. The first five rows appear. You notice a column of prices that looks like strings with dollar signs.
Step 3: Write a cleaning function. Press B to create a cell below, then Enter to edit. Type:
def clean_price(price_str):
return float(price_str.replace('$', '').replace(',', ''))
Press Shift+Enter. The function is defined.
Step 4: Apply it and time it. Press B, then Enter. This time, you want to know if your cleaning function is slow on a large dataset. Type:
%timeit df['price'].apply(clean_price)
Press Shift+Enter. The output: 2.34 ms ± 45 µs per loop. In plain English: “Cleaning 10,000 prices takes about 2.3 milliseconds. That’s fast enough—no need to optimize.”
Step 5: Debug an error. You try to create a new column, but you make a typo:
df['price_clean'] = df['price'].apply(clean_price)
df['revenue'] = df['price_clean'] * df['quantitty'] # typo: 'quantitty'
You run it with Shift+Enter. KeyError! But you turned on %pdb earlier, so you’re dropped into the debugger at the failing line. You type df.columns and immediately spot the typo: it should be 'quantity'. You type q to quit the debugger, fix the typo, and re-run.
Step 6: Write the cleaned data to disk. Press B for a new cell. This time, press M to switch it to markdown. Type a quick note: ## Save cleaned data. Press B again for a code cell below it. Type:
%%writefile cleaned_sales.csv
df.to_csv('cleaned_sales.csv', index=False)
Wait—that’s wrong. %%writefile writes the literal contents of the cell to a file, not the output of executing it. You catch yourself. Instead, just use pandas:
df.to_csv('cleaned_sales.csv', index=False)
Press Shift+Enter. Done.
Step 7: Check your workspace. You’ve created a bunch of variables. Press Esc to enter command mode, then type %whos in a new cell (press B, Enter, type %whos, Shift+Enter). You see df (DataFrame, 10000 rows), clean_price (function), and a few others. Everything looks clean.
Step 8: Review your workflow. You want to remember the exact sequence for your README. New cell: %history -g df. This shows every command that touched a DataFrame. You copy the relevant lines.
The rhythm becomes second nature: Esc to command mode, B or A to create cells, Enter to edit, Shift+Enter to execute and move on. Your hands never leave the keyboard.
Customizing a Shortcut That Doesn’t Exist
Here’s one that doesn’t have a default shortcut but should: “restart kernel and run all cells.” In JupyterLab, you can bind it yourself.
- Open Settings → Advanced Settings Editor → Keyboard Shortcuts.
- In the “User Preferences” tab, add a new entry:
{
"command": "runmenu:restart-and-run-all",
"keys": ["Ctrl Shift R"],
"selector": "body"
}
Now Ctrl+Shift+R restarts your kernel and re-runs every cell from top to bottom. In plain English: “Give me a completely fresh state and reproduce all my results with one keystroke.” This is invaluable when you’re about to share a notebook and want to confirm it runs cleanly from scratch.
Recap: What We Learned
- The two-mode system is the foundation. Edit mode (green border) is for typing. Command mode (grey border, blue margin) is for structural operations. Esc switches to command mode; Enter switches to edit mode. Everything else depends on knowing which mode you’re in.
- Command-mode shortcuts cover 80% of daily navigation. A (above), B (below), Y (code), M (markdown), D,D (delete), Z (undo delete), and Shift+Enter (run and move down) are the ones you’ll use every few seconds.
- Magic commands are meta-Python. Line magics (
%) apply to one line; cell magics (%%) apply to the whole cell and must be on the first line. Use%lsmagicto discover them and%magic_name?to learn them. - Four magics will change your debugging workflow.
%timeitfor reliable micro-benchmarking,%pdbfor automatic debugging on errors,%whosfor inspecting your namespace, and%autoreloadfor keeping imported modules in sync with their source files. - %autoreload requires the two-step dance.
%load_ext autoreloadloads the extension;%autoreload 2enables full auto-reloading. Both must run in every new kernel session unless you add them to your IPython startup profile. - JupyterLab and classic Notebook have different default shortcuts. Know which environment you’re in. Use the Command Palette (Ctrl+Shift+C) in JupyterLab to discover and customize shortcuts.
Check Your Understanding
Remember
- What key switches from edit mode to command mode?
- What’s the shortcut to insert a cell above the current one?
- What’s the shortcut to delete a selected cell?
Understand
- Why does
%%timeitrun the code multiple times instead of just once? What does the “±” in the output represent? - What’s the difference between
%timeitand%time? Why might you choose one over the other?
Apply
- You have a slow function in
helpers.py. You edit the file and save it, but your notebook still runs the old version. What two lines do you run to fix this without restarting the kernel?
Analyze
- You’re in JupyterLab, and pressing “A” in command mode doesn’t insert a cell above. What are two possible reasons?
Evaluate
- A colleague says, “
%timeitis always better than%timefor measuring performance.” Is this true? Describe a scenario where%timewould be the right choice.
Create
- Design a custom keyboard shortcut for JupyterLab that restarts the kernel and runs all cells. What command ID would you bind, and what key combination would you choose? Why that combination?
Apply What You Learned is for Supporter and Insider subscribers.
Subscribe to unlock the exercises on this post.
See plansRelated articles
- Python Engineering Under review
Matplotlib Vs Seaborn Vs Plotly Choosing The Right
Picture this: you've just finished cleaning a dataset. You're ready to explore. You open a Jupyter notebook and your cursor blinks at a blank code cell.
- Python Engineering Under review
Connecting Python To Mysql And Postgresql The Real
Think of connecting to a database like getting around a new city. You have two main options:
- Python Engineering Under review
Automl Tools Compared Google Aws Azure H2O And Aut
Think of building a machine learning pipeline like exploring a huge, dark room looking for a light switch.
- Python Engineering Under review
Python Ides Compared Pycharm Vs Vs Code Vs Jupyter
Before we dive deep, let’s get our bearings. Think of this table as your at-a-glance map—a one-sentence answer to “what is this thing, fundamentally?” for each tool.
Looking for something else?
Search every article by title, summary or topic.