Jupyter Notebook is the most popular interactive development environment in the fields of data science and machine learning. Mastering its shortcuts and techniques can significantly improve daily development efficiency.
You can click the Help menu to view keyboard shortcuts:
!(#)
!(#)
> All shortcuts in this article are based on **Windows/Linux**. Mac users should replace `Ctrl` with `Cmd` and `Alt` with `Option`.
* * *
## Two Operation Modes
Jupyter Notebook has two modes. **All shortcuts depend on the current mode**, which is the most easily overlooked key point for beginners:
| Mode | Cell Border Color | How to Enter | Function |
| --- | --- | --- | --- |
| **Command Mode** | Blue | Press `Esc` or click the left blank area of the Cell | Manage Cell operations (add, delete, move, etc.) |
| **Edit Mode** | Green | Press `Enter` or double-click inside the Cell | Write and modify code or text inside the Cell |
Simple memory aid: **Green = can type and edit; Blue = can manage Cells**. Before entering edit mode, first use `Esc` to exit, then use `Enter` to enter. Developing this habit can avoid a lot of misoperations.
* * *
## Shortcuts for Running Cells (Universal)
The following three shortcuts can be used in both modes. They are the most frequently used operations and must be memorized:
| Shortcut | Function | Use Case |
| --- | --- | --- |
| `Shift + Enter` | Run current Cell and automatically jump to the next Cell | Most commonly used, execute code sequentially downward |
| `Ctrl + Enter` | Run current Cell and stay at the current Cell | Used when repeatedly testing the same code |
| `Alt + Enter` | Run current Cell and insert a new Cell below | Used when running and adding new code blocks downward |
* * *
## Command Mode Shortcuts (Blue Border)
After pressing `Esc` to enter command mode, the following shortcuts can be used:
### 1. Cell Insertion and Deletion
| Shortcut | Function |
| --- | --- |
| `A` | Insert new Cell **Above** the current Cell |
| `B` | Insert new Cell **Below** the current Cell |
| `D, D` (press D twice) | Delete current Cell |
| `Z` | Undo deletion (restore just deleted Cell) |
| `X` | Cut current Cell |
| `C` | Copy current Cell |
| `V` | Paste Cell below the current Cell |
| `Shift + V` | Paste Cell above the current Cell |
### 2. Cell Type Switching
Cells in Jupyter have three types and can be switched at any time:
| Shortcut | Switch to | Purpose |
| --- | --- | --- |
| `Y` | Code | Write and run Python code |
| `M` | Markdown | Write formatted documents, titles, explanatory text |
| `R` | Raw | Output text as-is, without execution or rendering |
| `1` ~ `6` | Markdown heading levels H1 ~ H6 | Quickly set Cell to corresponding heading level (automatically switches to Markdown mode) |
### 3. Cell Selection and Merging
| Shortcut | Function |
| --- | --- |
| `β` / `K` | Select Cell above |
| `β` / `J` | Select Cell below |
| `Shift + β` / `Shift + K` | Continuously select multiple Cells upward |
| `Shift + β` / `Shift + J` | Continuously select multiple Cells downward |
| `Shift + M` | Merge selected multiple Cells into one |
### 4. Output and Display Control
| Shortcut | Function |
| --- | --- |
| `O` | Collapse/expand current Cell's output |
| `Shift + O` | Toggle scroll mode for current Cell's output area (used when output content is very long) |
| `L` | Show/hide line numbers for current Cell |
| `F` | Find and replace text in Cell |
### 5. Kernel and Interface Operations
| Shortcut | Function |
| --- | --- |
| `I, I` (press I twice) | Interrupt currently running Cell (equivalent to Ctrl+C) |
| `0, 0` (press 0 twice) | Restart kernel (clears all running variables, **use with caution**) |
| `H` | Open keyboard shortcuts help panel (displays all available shortcuts) |
| `P` | Open command palette, can search all Jupyter functions |
| `Space` | Scroll page down |
| `Shift + Space` | Scroll page up |
| `S` / `Ctrl + S` | Save Notebook |
* * *
## Edit Mode Shortcuts (Green Border)
After pressing `Enter` to enter edit mode, the following shortcuts can be used to operate inside the Cell:
### 1. Code Editing
| Shortcut | Function |
| --- | --- |
| `Tab` | Code auto-completion (press Tab to complete after typing partial function/variable name) |
| `Shift + Tab` | View parameter documentation for function at cursor (pop-up documentation hint, press once for brief, twice for full documentation) |
| `Ctrl + /` | Comment/uncomment current line or selected multiple lines of code |
| `Ctrl + D` | Delete current entire line |
| `Ctrl + Shift + -` | Split current Cell into two Cells at cursor position |
| `Ctrl + Z` | Undo (restore previous edit) |
| `Ctrl + Y` | Redo (cancel undo) |
| `Ctrl + A` | Select all content in current Cell |
| `Ctrl + Home` | Jump to beginning of Cell content |
| `Ctrl + End` | Jump to end of Cell content |
| `Ctrl + β` / `Ctrl + β` | Jump cursor by word (quickly move to previous/next word) |
### 2. Return from Edit Mode to Command Mode
| Shortcut | Function |
| --- | --- |
| `Esc` | Exit edit mode, return to command mode (Cell border turns blue) |
| `Ctrl + M` | Same as Esc, exit edit mode |
* * *
## Magic Commands
Magic commands are Jupyter's built-in special instructions, starting with `%` (single line) or `%%` (entire Cell), used to complete common tasks such as timing, debugging, and file operations. **No libraries need to be installed to use them**.
### 1. Code Timing
## Example
```python
# %timeit: Perform multiple repeated timings for single line of code, take average for more accurate results (suitable for testing performance of short expressions)
%timeit [x**2 for x in range(1000)]
# Output example: 98.3 Β΅s Β± 1.2 Β΅s per loop (mean Β± std. dev. of 7 runs, 10000 loops each)
# %%time: Time entire Cell's code only once (suitable for testing complete processes that take longer)
%%time
import time
data = [x**2 for x in range(100000)]
time.sleep(1)
# Output example:
# CPU times: user 45.2 ms, sys: 8.1 ms, total: 53.3 ms
# Wall time: 1.05 s
### 2. Inline Chart Display
## Example
```python
# %matplotlib inline: Embed charts directly in Notebook for display (most commonly used, static images)
# Usually placed in the first Cell of Notebook, only needs to be executed once for entire Notebook
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2 * np.pi, 100)
plt.plot(x, np.sin(x))
plt.title('Sine Wave')
plt.show()
# %matplotlib notebook: Enable interactive charts, can zoom and pan (but cannot be used simultaneously with inline)
# %matplotlib notebook
### 3. Viewing and Managing Variables
## Example
```python
# %who: List all defined variable names in current namespace
%who
# Output example: data plt x
# %whos: More detailed than %who, also shows variable types and values
%whos
# Output example:
# Variable Type Data/Info
# ----------------------------
# x ndarray 100: [0. 0.06 ... 6.28]
# data list n=100000
# %reset: Clear all variables (will pop up confirmation prompt, suitable for restarting calculations)
%reset
# %reset -f: Force clear all variables without confirmation prompt (-f means force)
%reset -f
### 4. File and Path Operations
## Example
```python
# %pwd: Display current working directory (Print Working Directory)
%pwd
# Output example: '/home/user/notebooks'
# %ls: List all files in current directory (Windows users may need to use %ls or directly use !dir)
%ls
# Output example: data.csv model.py notebook.ipynb
# %%writefile: Write entire Cell's content to specified file (commonly used for quickly creating script files)
%%writefile hello.py
def greet(name):
print(f"Hello, {name}!")
greet("World")
# After execution, hello.py file will be generated in current directory with content being the code in Cell
# %run: Run an external Python script file and import its variables into current namespace
%run hello.py
# Output: Hello, World!
# %load: Load content of external script file into current Cell (will not auto-execute, only loads code)
%load hello.py
### 5. System Command Execution
## Example
```python
# Adding ! before command can directly execute system terminal commands without switching to terminal window
!pip install pandas # Install Python package
!pip list # View installed package list
!python --version # View Python version
# Can also save command output results as Python variables
files = !ls -1 # Execute ls command, assign result to files variable
print(files) # files is a list, each filename is an element
### 6. Viewing History and Debugging
## Example
```python
# %history: View all command history executed in this session
%history
# Add -n to show line numbers, add -l 5 to show only last 5 entries
%history -n -l 5
# %debug: After code error, execute %debug in next Cell to enter interactive debugging mode
# Can input variable names to view values in debugging mode, input q to exit debugging
# For example, after running code that produced an error:
%debug
### 7. Rendering Special Content
## Example
```python
# %%html: Render Cell content as HTML output (can embed custom styles and interactive elements)
%%html
This is an HTML heading
Can directly render HTML content in Notebook.
# %%latex: Render Cell content as LaTeX formula (commonly used for writing mathematical formulas)
%%latex
$$E = mc^2$$
$$int_0^infty e^{-x^2} dx = frac{sqrt{pi}}{2}$$
* * *
## Real-time Progress Monitoring
When processing large amounts of data or during long loops, real-time progress monitoring is very important. Here are several commonly used progress display solutions.
### 1. tqdm Progress Bar (Recommended)
tqdm is the most commonly used progress bar library, supporting loops, Pandas, and various Jupyter scenarios. Installation command:
```bash
pip install tqdm
## Example
```python
from tqdm.notebook import tqdm # Use notebook version in Jupyter for better visual effect
import time
# Basic usage: Wrap iterable object in tqdm() to automatically display progress bar
for i in tqdm(range(100)):
time.sleep(0.05) # Simulate time-consuming operation
# Output: Display progress bar, completed percentage, elapsed time, estimated remaining time
# Use with enumerate
data = list(range(50))
for i, item in enumerate(tqdm(data, desc="Processing data")):
# desc parameter sets label text on left side of progress bar
time.sleep(0.05)
# Manual progress control (suitable for scenarios with uncertain total amount)
with tqdm(total=100, desc="Download progress") as pbar:
for chunk in range(10):
time.sleep(0.1)
pbar.update(10) # Update progress by 10 units each time
pbar.set_postfix({"chunk": chunk}) # Display additional info on right side of progress bar
## Example
```python
# tqdm integration with Pandas: Display progress for DataFrame apply operations
import pandas as pd
from tqdm.notebook import tqdm
tqdm.pandas() # Enable Pandas integration, only needs to be executed once
df = pd.DataFrame({'value': range(1000)})
# Use progress_apply instead of regular apply to automatically display progress
result = df['value'].progress_apply(lambda x: x ** 2)
### 2. display + clear_output Dynamic Refresh Output
When you don't want to install tqdm, you can use IPython's built-in `clear_output` to achieve dynamic refresh effect:
## Example
```python
from IPython.display import clear_output
import time
total = 50
for i in range(total):
time.sleep(0.1)
# clear_output(wait=True): Clear previous output, wait=True means wait until new content before clearing,
# avoiding flickering. Note: This will clear all output of current Cell
clear_output(wait=True)
# Manually draw a simple text progress bar
done = int((i + 1) / total * 30) # Calculate completed blocks (30 blocks total)
bar = 'β' * done + 'β' * (30 - done) # β means completed, β means not completed
pct = (i + 1) / total * 100
print(f"Progress: [{bar}] {pct:.1f}% ({i+1}/{total})")
print("β
All completed!")
### 3. Real-time Chart Progress
In scenarios such as model training, you can dynamically update charts at intervals to observe metric trends in real-time:
## Example
```python
%matplotlib inline
import matplotlib.pyplot as plt
from IPython.display import clear_output, display
import numpy as np
import time
losses = [] # Store loss values at each step, simulating training process
for step in range(50):
# Simulate training: generate a gradually decreasing loss value
loss = 1 / (step + 1) + np.random.uniform(0, 0.05)
losses.append(loss)
# Update chart every 5 steps to avoid too frequent refreshing
if (step + 1) % 5 == 0:
clear_output(wait=True)
fig, ax = plt.subplots(figsize=(8, 4))
ax.plot(losses, color='steelblue', linewidth=2)
ax.set_title(f'Training Progress (Step {step + 1}/50)')
ax.set_xlabel('Step')
ax.set_ylabel('Loss')
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show() # Call show after clear_output, chart will refresh at same position
time.sleep(0.1)
print("Training completed! Final Loss:", f"{losses:.4f}")
* * *
## Tips for Viewing Documentation and Code
### 1. Quick Function Documentation Viewing
## Example
```python
# Method 1: After function name