Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Jupyter Notebook Shortcuts and Practical Tips

Jupyter Notebook Shortcuts and Practical Tips

Jupyter Notebook is the most popular interactive development environment in data science and machine learning. Mastering its shortcuts and tips greatly improves day-to-day efficiency.

You can click the Help menu to view the shortcuts:

All shortcuts in this article are based on Windows/Linux . Mac users should replace Ctrl with Cmd, and replace Alt with Option.


Two operating modes

Jupyter Notebook has two modes,all shortcuts depend on the mode you are currently in, which is the key point beginners most easily overlook:

Mode Cell border color How to enter Purpose
Command Mode Blue Press Esc or click the blank area on the left of the Cell Manage Cells (add, delete, move and so on)
Edit Mode Green Press Enter or double-click inside the Cell Write and modify code or text inside the Cell

Simple rule:Green = you can type and edit; Blue = you can manage Cells. Before entering Edit Mode, first use Esc to exit, then use Enter to enter; making this a habit avoids many accidental operations.


Shortcuts for running Cells (universal)

The following three shortcuts work in both modes; they are the most frequently used operations, so memorize them:

Keyboard shortcut Purpose Applicable scenarios
Shift + Enter Run the current Cell and jump to the next Cell automatically Most commonly used; execute code downwards in order
Ctrl + Enter Run the current Cell and stay on the current Cell Used when repeatedly testing the same piece of code
Alt + Enter Run the current Cell and insert a new Cell below Used when adding new code blocks while running downwards

Command Mode shortcuts (blue border)

Press Esc After entering Command Mode, you can use these shortcuts:

1. Inserting and deleting Cells

Keyboard shortcut Purpose
A In the current Cell aboveinsert a new Cell (Above)
B In the current Cell belowinsert a new Cell (Below)
D, D(press D twice) delete the current Cell
Z undo a deletion (restore the Cell just deleted)
X cut the current Cell
C copy the current Cell
V paste a Cell below the current Cell
Shift + V paste a Cell above the current Cell

2. Switching Cell types

Cells in Jupyter have three types and can be switched at any time:

Keyboard shortcut Switch to Purpose
Y Code write and run Python code
M Markdown write formatted documents, headings and explanatory text
R Raw output text as-is, neither executed nor rendered
1 ~ 6 Markdown heading levels H1 to H6 quickly set a Cell to the corresponding heading level (automatically switches to Markdown mode)

3. Selecting and merging Cells

Keyboard shortcut Purpose
↑ / K select the Cell above
↓ / J select the Cell below
Shift + ↑ / Shift + K select multiple Cells upwards
Shift + ↓ / Shift + J select multiple Cells downwards
Shift + M merge the selected Cells into one

4. Output and display control

Keyboard shortcut Purpose
O collapse/expand the output of the current Cell
Shift + O toggle scrolling for the current Cell's output area (useful when output is long)
L show/hide line numbers in the current Cell
F find and replace text in a Cell

5. Kernel and interface operations

Keyboard shortcut Purpose
I, I(press I twice) interrupt the currently running Cell (equivalent to Ctrl+C)
0, 0(press 0 twice) restart the kernel (clears all variables that have been run,Use with Caution)
H open the shortcut help panel (shows all available shortcuts)
P open the command palette to search all Jupyter features
Space scroll the page down
Shift + Space scroll the page up
S / Ctrl + S save the Notebook

Edit Mode shortcuts (green border)

Press Enter After entering Edit Mode, you can use these shortcuts inside a Cell:

1. Code editing

Keyboard shortcut Purpose
Tab code auto-completion (type part of a function or variable name and press Tab to complete)
Shift + Tab view the parameter documentation of the function at the cursor (a doc popup; press once for a brief version, twice for the full documentation)
Ctrl + / comment/uncomment the current line or multiple selected lines
Ctrl + D delete the entire current line
Ctrl + Shift + - split the current Cell into two Cells at the cursor
Ctrl + Z undo (restore the previous edit)
Ctrl + Y redo (cancel an undo)
Ctrl + A select all content in the current Cell
Ctrl + Home jump to the very beginning of the Cell content
Ctrl + End jump to the very end of the Cell content
Ctrl + ← / Ctrl + → move the cursor by word (quickly jump to the previous/next word)

2. Returning to Command Mode from Edit Mode

Keyboard shortcut Purpose
Esc exit Edit Mode and return to Command Mode (Cell border turns blue)
Ctrl + M same as Esc, exit Edit Mode

Magic Commands

Magic commands are special built-in Jupyter instructions that start with %(single line) or %%(whole Cell); they handle common tasks such as timing, debugging and file operations,and work without installing any library.

1. Code timing

Example

%timeit: times a single line of code repeatedly and takes the average, which is more accurate (good for testing the 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: times the whole Cell's code only once (good for long-running complete workflows)

%%

time

import

time

data

=

[

x**

2

for

x

in

range

(

100000

)

]

time

.

sleep

(

1

)

Example output:

CPU times: user 45.2 ms, sys: 8.1 ms, total: 53.3 ms

Wall time: 1.05 s

2. Inline charts

Example

%matplotlib inline: embeds charts directly in the Notebook for display (most commonly used, static images)

usually placed in the first Cell of the Notebook; the whole Notebook only needs to run it once

%matplotlib inline

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

x

=

np.

linspace

(

0

,

2

pi

,

100

)

plt.

plot

(

x

,

np.

sin

(

x

)

)

plt.

title

(

'Sine wave'

)

plt.

show

(

)

%matplotlib notebook: enables interactive charts that can be zoomed and panned (but cannot be used together with inline)

%matplotlib notebook

3. Viewing and managing variables

Example

%who: lists the names of all variables defined in the current namespace

%who

Output example: data plt x

%whos: more detailed than %who, also showing each variable's type and value

%whos

Example output:

Variable   Type    Data/Info

----------------------------

x          ndarray 100: [0. 0.06 ... 6.28]

data       list    n=100000

%reset: clears all variables (shows a confirmation prompt; useful when starting a computation over)

%reset

%reset -f: force-clears all variables without a confirmation prompt (-f means force)

%reset -f

4. File and path operations

Example

%pwd: shows the current working directory (Print Working Directory)

%

pwd

Output example: '/home/user/notebooks'

%ls: lists all files in the current directory (Windows users may need %ls or just !dir)

%ls

Output example: data.csv model.py notebook.ipynb

%%writefile: writes the whole Cell's content to a specified file (often used to create a script file quickly)

%%writefile hello.

py

def

greet

(

name

)

:

   

print

(

f

"Hello, {name}!"

)

greet

(

"World"

)

After running, a hello.py file is generated in the current directory containing the code from the Cell

%run: runs an external Python script file and imports its variables into the current namespace

%run hello.

py

Output: Hello, World!

%load: loads the content of an external script file into the current Cell (does not run it automatically, only loads the code)

%load hello.

py

5. Running system commands

Example

Prefixing a command with ! lets you run a system terminal command directly without switching to a terminal window

!

pip install pandas          

install a Python package

!

pip

list

                   

view the list of installed packages

!

python --version            

Check the Python version

you can also save command output into a Python variable

files

=

!

ls -

1

             

run the ls command and assign the result to the files variable

print

(

files

)

               

files is a list, with each filename as an element

6. History and debugging

Example

%history: view the command history of all commands executed in this session

%history

add -n to show line numbers, add -l 5 to show only the most recent 5 entries

%history -n -l

5

%debug: after code raises an error, running %debug in the next Cell enters interactive debugging mode

in debug mode you can type a variable name to see its value, and type q to quit debugging

for example, after running a piece of code that raises an error:

%debug

7. Rendering special content

Example

%%html: renders the Cell content as HTML output (you can embed custom styles and interactive elements)

%%html

<

h3 style

=

"color: steelblue;"

This is an HTML heading

<

/h3

<

p style

=

"font-size: 16px;"

HTML content can be rendered directly in the Notebook.

<

/p

%%latex

$$E

=

mc^

2

$$

$$\int_0^\infty e^

{

-x^

2

}

dx

=

\frac

{

\sqrt

{

\pi

}

}

{

2

}

$$


View run progress in real time

When processing large amounts of data or long loops, seeing progress in real time is very important. Here are several common ways to display it.

1. tqdm progress bar (recommended)

tqdm is the most commonly used progress bar library, supporting loops, Pandas and many Jupyter scenarios; install it with:

pip install tqdm

Example

from

tqdm.

notebook

import

tqdm  

in Jupyter use the notebook version for a better-looking display

import

time

basic usage: wrap an iterable in tqdm() and a progress bar appears automatically

for

i

in

tqdm

(

range

(

100

)

)

:

   

time

.

sleep

(

0.05

)

   

simulate a time-consuming operation

Output: shows a progress bar, percentage completed, elapsed time and estimated remaining time

used together with enumerate

data

=

list

(

range

(

50

)

)

for

i

,

item

in

enumerate

(

tqdm

(

data

,

desc

=

"Processing data"

)

)

:

   

the desc parameter sets the label text on the left of the progress bar

   

time

.

sleep

(

0.05

)

manual progress control (for cases where the total is unknown)

with

tqdm

(

total

=

100

,

desc

=

"Download progress"

)

as

pbar:

   

for

chunk

in

range

(

10

)

:

       

time

.

sleep

(

0.1

)

        pbar.

update

(

10

)

   

advance the progress bar by 10 units each time

        pbar.

set_postfix

(

{

"chunk"

:

chunk

}

)

 

show extra information on the right of the progress bar

Example

tqdm and Pandas integration: show progress for apply operations on a DataFrame

import

pandas

as

pd

from

tqdm.

notebook

import

tqdm

tqdm.

pandas

(

)

 

enable Pandas integration; only needs to run once

df

=

pd.

DataFrame

(

{

'value'

:

range

(

1000

)

}

)

use progress_apply instead of the ordinary apply to show progress automatically

result

=

df

[

'value'

]

.

progress_apply

(

lambda

x: x **

2

)

2. display + clear_output for dynamic refresh

When you do not want to install tqdm, use IPython's built-in clear_output to achieve a dynamic refresh effect:

Example

from

IPython.

display

import

clear_output

import

time

total

=

50

for

i

in

range

(

total

)

:

   

time

.

sleep

(

0.1

)

   

   

clear_output(wait=True): clears the previous output; wait=True means wait until new content arrives before clearing,

   

avoiding flicker. Note: this clears all output of the current Cell

    clear_output

(

wait

=

True

)

   

   

manually draw a simple text progress bar

    done

=

int

(

(

i +

1

)

/ total *

30

)

     

calculate the number of completed slots (30 slots in total)

    bar

=

'█'

'░'

(

30

)

 

a filled block means completed, a light block means not completed

    pct

=

(

i +

1

)

/ total *

100

   

print

(

f

"Progress: [{bar}] {pct:.1f}% ({i+1}/{total})"

)

print

(

"All done!"

)

3. Live chart progress

In scenarios such as model training, you can update a chart periodically to watch metrics change in real time:

Example

%matplotlib inline

import

matplotlib.

pyplot

as

plt

from

IPython.

display

import

clear_output

,

display

import

numpy

as

np

import

time

losses

=

[

]

   

store the loss value of each step to simulate training

for

step

in

range

(

50

)

:

   

simulate training: generate a gradually decreasing loss value

    loss

=

1

/

(

step +

1

)

random

.

uniform

(

0

,

0.05

)

    losses.

append

(

loss

)

   

   

update the chart every 5 steps to avoid refreshing too often

   

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 so the chart refreshes in the same position

   

   

time

.

sleep

(

0.1

)

print

(

"Training complete! Final loss:"

,

f

"{losses[-1]:.4f}"

)


Tips for viewing documentation and code

1. Quickly view function documentation

Example

Method 1: add ? after a function name to open a documentation panel at the bottom of the Notebook

import

numpy

as

np

np.

array

?

shows the parameter description and functionality of np.array

Method 2: add ?? after a function name to show the full documentation, including source code (if available)

np.

array

??

Method 3: press Shift + Tab inside the function parentheses

for example, after typing np.linspace( (inside the parentheses), press Shift + Tab to show a parameter hint

press Shift + Tab twice to show more complete documentation

Method 4: use the help() function (output is more complete, but appears in the output area rather than a popup)

help

(

np.

array

)

2. Display multiple outputs with display

By default Jupyter shows only the value of the last expression in each Cell. Through display() you can output several results in one Cell:

Example

import

pandas

as

pd

from

IPython.

display

import

display

df1

=

pd.

DataFrame

(

{

'A'

:

[

1

,

2

,

3

]

,

'B'

:

[

4

,

5

,

6

]

}

)

df2

=

pd.

DataFrame

(

{

'X'

:

[

7

,

8

,

9

]

,

'Y'

:

[

10

,

11

,

12

]

}

)

without display, only the last DataFrame is shown

df1 # not displayed

df2 # only this one is displayed

using display() can show several tables at once, nicely formatted

display

(

df1

)

display

(

df2

)

Example

Tip: change the Notebook configuration so every expression's value is displayed automatically (no need to call display manually)

from

IPython.

core

.

interactiveshell

import

InteractiveShell

InteractiveShell.

ast_node_interactivity

=

"all"

   

the default is "last_expr"; after changing it to "all"

                                                   

every expression in the Cell outputs its result automatically

1

1

     

Output 2

2

2

     

outputs 4 (this line is not displayed by default)

"hello"

   

outputs 'hello'

3. Suppressing unwanted output

Example

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Problem: plt.plot() displays the chart but also prints a redundant object description, such as:

[]

Solution: add a semicolon (;) at the end of the statement to suppress the output of the last expression without affecting the chart

plt.

plot

(

np.

sin

(

np.

linspace

(

0

,

2

*np.

pi

,

100

)

)

)

;

with the semicolon the chart still displays, but the redundant object description does not appear


Other practical tips

1. Inspect intermediate variable values (without interrupting execution)

Example

Tip: use the fact that a Python assignment can also return a value,

assign the intermediate result to a variable and wrap the whole line in parentheses so it is printed

import

numpy

as

np

ordinary way (you cannot see the value of result)

result

=

np.

array

(

[

1

,

2

,

3

]

)

2

parenthesized way (prints the value of result while assigning it)

(

result :

=

np.

array

(

[

1

,

2

,

3

]

)

2

)

   

Python 3.8+ walrus operator style

Output: array([2, 4, 6])

or more simply: just write the variable name on a new line after the assignment

result

=

np.

array

(

[

1

,

2

,

3

]

)

2

result      

Jupyter automatically displays the value of the last expression

2. Referencing the previous output

Example

Jupyter has built-in special variables for quickly referencing historical output:

_ : the output of the previous Cell

__ : the output of the Cell before last

_3 : the output of the 3rd Cell (Out[3]) (the number matches the Out index on the left)

For example:

1

1

Out[1]: 2

_        

reference the previous output, whose value is 2

Out[2]: 2

_ *

10

   

continue computing with the previous output

Out[3]: 20

_3 +

5

   

reference the Out[3] result 20 and add 5

Out[4]: 25

3. Displaying rich text in a Notebook

Example

from

IPython.

display

import

display

,

HTML

,

Image

,

Markdown

,

Audio

,

Video

render Markdown formatted text

display

(

Markdown

(

"## This is a heading\n\nBold text, Italic text, 代码"

)

)

Render HTML

display

(

HTML

(

"Large red text"

)

)

Display an online image (pass an image URL)

display

(

Image

(

url

=

"https://www.runoob.com/images/runoob-logo.png"

,

width

=

200

)

)

Display a local image (pass a local file path)

display(Image(filename="./chart.png"))

4. Adding timing annotations to a Cell (show elapsed time in the output automatically)

Example

installing jupyter-contrib-nbextensions gives you more extension features

pip install jupyter-contrib-nbextensions

simple approach: wrap the timing logic in a decorator or context manager and use it in any code block

import

time

from

contextlib

import

contextmanager

@

contextmanager

def

timer

(

label

=

"Elapsed time"

)

:

    start

=

time

.

time

(

)

   

try

:

       

yield

   

finally

:

        elapsed

=

time

.

time

(

)

       

print

(

f

"{label}: {elapsed:.3f} seconds"

)

usage: wrap any code block with with timer() and the elapsed time is printed automatically when it finishes

with

timer

(

"Data processing"

)

:

    data

=

[

x **

2

for

x

in

range

(

1000000

)

]

Output: Data processing: 0.087 seconds

5. Quickly view all shortcuts in the current Notebook

In Command Mode (blue border) press H, or use the menu Help → Keyboard Shortcutsto open the full shortcut help panel and look up any available operation at any time.


Common shortcut quick reference

Operation Keyboard shortcut Mode
Run Cell and jump to the next Shift + Enter Universal
Run Cell and stay in place Ctrl + Enter Universal
Run Cell and create a new one below Alt + Enter Universal
Enter Edit Mode Enter Command Mode
Exit Edit Mode Esc Edit Mode
Insert Cell above A Command Mode
Insert Cell below B Command Mode
Delete Cell D, D Command Mode
Undo Cell deletion Z Command Mode
Switch to a Code Cell Y Command Mode
Switch to a Markdown Cell M Command Mode
Merge multiple selected Cells Shift + M Command Mode
Interrupt the kernel (stop running) I, I Command Mode
Restart the kernel 0, 0 Command Mode
Show shortcut help H Command Mode
Code auto-completion Tab Edit Mode
View function parameters/documentation Shift + Tab Edit Mode
Comment/uncomment Ctrl + / Edit Mode
Split Cell at the cursor Ctrl + Shift + - Edit Mode
save the Notebook S / Ctrl + S Command Mode / Edit Mode