Of course! You're asking about IPython line magics. They are a powerful feature of the IPython environment (which is the foundation for Jupyter Notebooks and IPython terminals) that allows you to execute special commands with a simple, shorthand syntax.

Here's a comprehensive guide covering what they are, how to use them, and the most common examples.
What are Line Magics?
Line magics are commands that are prefixed with a single percent sign () and operate on a single line of input. They are shortcuts for common tasks that would otherwise require writing more Python code or using external tools.
Key Characteristics:
- Syntax:
%command [arguments] - Scope: Operate on the line of code they are in.
- Execution: They are processed by IPython before the code is passed to the Python interpreter.
How to Use Line Magics
You can use them directly in any IPython environment.

In a Jupyter Notebook or JupyterLab:
This is the most common place you'll encounter line magics.
# In a Jupyter Notebook cell %timeit my_list = [i**2 for i in range(100)]
In an IPython Terminal:
If you start your Python session with the ipython command, you can use magics directly.
$ ipython Python 3.9.7 (default, Sep 10 2025, 14:59:43) Type 'copyright', 'credits' or 'license' for more information IPython 8.4.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: %pwd Out[1]: '/home/user/projects' In [2]: %ls data.csv my_script.py notebook.ipynb
In a Standard Python Script (.py file):
You can also use magics in regular Python scripts. This is done with the magic, but for line magics, you need to enable them first by adding a special import at the top of your file.
# my_script.py
# This line is crucial for magics to work in a .py file
%matplotlib inline
import matplotlib.pyplot as plt
# Now you can use other magics
%run helper_script.py
print("Hello from the main script!")
To run this script, you must use ipython instead of python:
$ ipython my_script.py
Common and Useful Line Magics
Here are some of the most frequently used line magics, categorized by their function.
Running Code
-
%run: Executes a Python script in the current namespace.# Run another script. Its variables will be available here. %run my_other_script.py
-
%load: Loads code from a file into a cell.# Load the contents of 'my_function.py' into this cell %load my_function.py
Timing and Profiling
-
%time: Times the execution of a single statement.%time import math
Output:
CPU times: user 2 µs, sys: 1 µs, total: 3 µs Wall time: 5.01 µs -
%timeit: Times the execution of a statement multiple times to get a more reliable average (great for short snippets).%timeit [i**2 for i in range(100)]
Output:
10000 loops, best of 5: 22.7 µs per loop -
%prun: Runs a statement under the profiler to show detailed statistics on function calls.def slow_function(n): total = 0 for i in range(n): total += i return total %prun slow_function(1000000)Output:
4 function calls in 0.042 seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 1 0.042 0.042 0.042 0.042 <ipython-input-1-...>:1(slow_function) 1 0.000 0.000 0.042 0.042 <string>:1(<module>) 1 0.000 0.000 0.042 0.042 {built-in method builtins.exec} 1 0.000 0.000 0.042 0.042 {built-in method builtins.len}
Environment and Namespace Inspection
-
%who/%whos: Lists variables in the global namespace.%who: Simple list of variable names.%whos: More detailed list (type, size, value).x = 10 y = "hello" z = [1, 2, 3]
%whos
*Output:*Variable Type Data/Info
x int 10 y str hello z list [1, 2, 3]
-
%reset: Resets the namespace by removing all user-defined variables.# Use with caution! It will delete all your variables. # %reset
-
%env: Gets or sets environment variables.# Get a specific environment variable %env HOME # Set an environment variable %env API_KEY=12345
File and Directory Operations
-
%pwd: Prints the current working directory.%pwd
-
%ls: Lists the files in the current directory (likelsin Unix ordirin Windows).%ls
-
%cd: Changes the current working directory.# Change to the 'data' directory %cd data
System Shell Commands
-
This is technically not a line magic but a related feature. It lets you execute shell commands directly.
# List files using the shell command !ls # Get the current git branch !git branch
Help and Documentation
-
%quickref: Shows a quick reference card for all IPython magics. -
%magic: Shows a detailed description of all available magics. -
and : The help operator.
# Get the docstring for a magic %timeit? # Get the full source code for a magic (if available) %timeit??
The Difference: Line Magic () vs. Cell Magic ()
It's crucial to understand the difference between line and cell magics.
| Feature | Line Magic () | Cell Magic () |
|---|---|---|
| Prefix | (one percent) | (two percents) |
| Scope | Applies to the rest of the line it is on. | Applies to the entire cell it is in. |
| Syntax | %command [code] |
%%command[code line 1][code line 2] |
| Example | %timeit sum(range(100)) |
%%timeittotal = 0for i in range(100):total += i |
| Use Case | Quick, single-line operations. | Multi-line operations like embedding visualizations or writing to a file. |
Example of a Cell Magic (%%writefile):
This magic writes the contents of the cell to a file.
%%writefile my_new_file.txt This is the first line of my file. This is the second line. And this is the third.
Output:
Writing my_new_file.txt
Getting Help and Discovering Magics
The best way to learn about magics is to explore them directly in IPython.
-
List all magics:
%lsmagic
This will give you a list of all available line and cell magics.
-
Get help for a specific magic:
%timeit?
This will display the docstring for the
%timeitmagic, explaining its arguments and usage.
Summary
IPython line magics are a fantastic productivity tool that makes interactive computing in Python much more efficient. They provide quick access to system commands, timing, debugging, and file operations without leaving the comfort of your Python environment. Mastering a few key ones like %timeit, %run, %whos, and %ls will significantly speed up your workflow.
