ipythonipython-magic

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?


Solution

  • 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