Saturday, September 13

Python syntax highlighting in LaTeX

LaTeX provides a listings package to typeset code. The standard output is great for black-and-white printouts, but not for beamer presentations, where a more dynamic color scheme would be suitable. Having recently worked on slides with Python code, I have prepared a file that you can include to get nice colourful code that looks good on a presentation:

My code is based on a snippet found on Ubuntu forums. I added some more keywords and tweaked the color scheme to correspond to the one that IDLE uses (that color scheme is not ideal, but my audience uses IDLE for coding and I wanted some consistency).

To use the package, copy the file to the same folder as your document and include it in the header:


Then, to render code, use python sections:

def foo():
    print "bar"

Note that if you want to use this in a beamer frame, you will have to mark the frame that contains Python code as fragile, like this:

\begin{frame}[fragile]{Some Python code}

def foo():
    print "bar"



Edgar Marca said...

Hi thanks for this code, it didn't work in my computer there is a problem with orange color. I have to add \definecolor{orange}{rgb}{1,0.5,0} and now it works.

Helder Silva said...

Great improvement!
I was reading the listings manual. Do you know how to activate the lstinput for your new definitions?

The purpose is to use:



Gintautas Miliauskas said...

Sorry, I'm not sure what to do about lstinputlisting. I took a quick stab, but without results, and I do not have the time to look closer into this right now. It's definitely possible though, documentation should help.

David Kofoed Wind said...

How could I apply a background color to the code box?

Maarten Bosmans said...


seems to work

Thomas Lechauve said...

Hi !
Thanks a lot for your snippet,
very simple and very useful =)

Olivier Verdier said...
This comment has been removed by the author.
Olivier Verdier said...

I've published a similar package on github.

Anonymous said...

It's very useful, thanks
Is there a way to change the fontsize?
I'd like to make it a little smaller in order to add comments on the code.

Marilyn said...

Thank you so much.

I like to include output, and I'm looking for a way to highlight what the user typed.

Can you suggest a way to do that?

caiyan said...

kate spade outlet
michael kors outlet
yeezy 350 boost
swarovski crystal
ray ban sunglasses outlet
true religion outlet
ray ban sunglasses
toms outlet
chaussures louboutin
coach outlet store