Write Beautiful Python Code In LaTeX

A quick tutorial on incorporating automatically formatted- and colored code snippets in your LaTeX editor

Wouter van Heeswijk, PhD
Geek Culture

--

Photo by Maskmedicare Shop on Unsplash

If your daily life involves mathematics and/or computer science in any capacity, chances are you use LaTeX for your writing. Although it comes with a bit of a learning curve, it offers precise control over your mathematics formulations, and the results look much better than in Word.

Naturally, we’d like the code snippets our LaTeX documents to look as good as the mathematics, but in this case support falls short. Sure, you could make a screenshot of your code, but (i) it will look grainy when zoomed in at 800% and (ii) you can’t copy-paste it. Manually editing the code is not very appealing either: inserting all indents, embedding the coloring nuances of documentation, functions, loops and numerical values… Not the kind of tasks most of us like to spend time on.

Fortunately, there is a simple solution: the Pygments library! It is a syntax highlighting package written in Python, which writes output in (among others) LaTeX format. To actually use the library in LaTex, we use the Minted package.

Setup

Let’s set it up.

  1. First, we install Pygments in the terminal: pip install Pygments

--

--