Did you always want to transform Python code into readable LaTeX output? latexify_py is the perfect way to do that!

Installation 💻

In order to install latexify_py, you type in the following command into your terminal.

!pip install latexify-py

Do not do this inside your Jupyter Notebook. Do the following:

# Install a pip package in the current Jupyter kernel
import sys
!{sys.executable} -m pip install latexify-py

Examples 👇

Before running your Python cells, make sure the following modules are activated.

import math
import latexify

Let's start with the first example.

def solve(a, b, c):
  return (-b + math.sqrt(b**2 - 4*a*c)) / (2*a)

We can now check the output of the function and print some statements.

print(solve(1, 4, 3))

The output would be:

If you call


it will output the code in LaTeX format.

LaTeX output from Python code.
def greek(alpha, beta, gamma, Omega):
  return alpha * beta + math.gamma(gamma) + Omega

Some math symbols such as Greek letters are converted automatically.

You can run the code yourself using the Colab Notebook below.

Alternative Render Methods 🖼

There are some commands inside Jupyter that output LaTeX code  %%latex cell magic just interprets the input in the cell as LaTeX code, it does not run any Python code.

Jupyter Notebook support the display of mathematical expressions typeset in LaTeX, which is rendered in the browser thanks to the MathJax library and is rendered inside HTML / Markdown.

Just put your LaTeX math inside dollar signs $ $ or enter in display math mode by writing inside double dollar signs.

from IPython.display import Math
Math(r'F(k) = \int_{-\infty}^{\infty} f(x) e^{2\pi i k} dx')

Or you can enter latex directly with the %%latex command.

\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} & = \frac{4\pi}{c}\vec{\mathbf{j}} \\
\nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\
\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\
\nabla \cdot \vec{\mathbf{B}} & = 0

If this post was helpful to you, consider subscribing to receive the latest blogs, tutorials and course updates! 🙂

And if you would love to see other blog posts or tutorials on AI, please leave a comment under this post - cheers!

Keep engineering your mind! ❤️