Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between % and %% in ipython magic commands

What difference does it make to use %timeit and %%timeit in ipython? Because when I read the documentation using ?%timeit and ?%%timeit it was the same documentation. So, what difference does adding % as prefix make?

like image 709
bigbounty Avatar asked Apr 06 '26 17:04

bigbounty


1 Answers

In general, one percentage sign is referred to as line magic and applies just to code that follows it on that same line. Two percentage signs is referred to as cell magic and applies to everything that follows in that entire cell.

As nicely put in The Data Science Handbook:

Magic commands come in two flavors: line magics, which are denoted by a single % prefix and operate on a single line of input, and cell magics, which are denoted by a double %% prefix and operate on multiple lines of input.

Some magic commands, like timeit, can work as line magic or cell magic:

Used as line magic:

%timeit y = 2 if x < 3 else 4

Used as cell magic:

%%timeit
if x < 3:
    y=2
else:
    y=4
like image 109
eric Avatar answered Apr 08 '26 19:04

eric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!