All courses available in-class and remotely.

Magic header

Python Magic Commands in Jupyter

June 15, 2021
Python users who work in Jupyter computational notebooks have access to an extra collection of commands, known as magic commands. Magic commands are an enhancement of the interactive IPython kernel (used by Jupyter) and make performing common tasks easier than using Python code alone.

Line magics and cell magics

Magic commands are easily identified because they all start with the % character. Line magics start with a single % and apply to the code on the rest of the line. Cell magics start with %% and apply to the rest of the code in a cell.

Below is a list of some of the built-in magic commands that I have found most useful. As with all Python functionality, more magic commands can be accessed from user-contributed packages.


How fast is your code?

Measuring execution time can help you optimise the performance of your code. Use the magic command %timeit (written at the beginning of a line of code) to return the time it takes to run that line of code. For multiple lines of code, use %%timeit.

Which is faster, a list comprehension or a for loop?

magic screenshot 1
magic screenshot 1



Autocomplete not working (especially with pandas)?

Often the solution is to simply disable the Jedi library autocomplete:

magic screenshot 2


Write your code to a file

Want to save code in a notebook cell to a .py file? Use the %%writefile magic command. This is a great way to save custom functions into a file for reuse later.

magic screenshot 3


Reload code from a file

Code can be loaded into a Notebook cell from a .py file using %load.

magic screenshot 4

When the code is run, the lines below the magic command will contain the code from the file.

magic screenshot 5


Want to see variables you’ve created?

The %who magic commands return the variables in various forms and can be used to return specific types of variables.

magic screenshot 6

 

magic screenshot 6

For more information on the built-in magic commands check out the IPython documentation.

Learn more about Python check out our Python Training Courses. Available in person in our CBD locations or remote online across Australia. 

Contact Us

What is Remote Training?

Valued by Individuals

4.72 / 5
Over 30777 Reviews

Trusted by Business

Procured by Government

Awards and Accreditations

Follow us