A Heap of Trouble

A Python Brain Teaser

Miki Tebeka
The Pragmatic Programmers
2 min readOct 11, 2021

--

Photo by Markus Spiske on Unsplash

📚 Connect with us. Want to hear what’s new at The Pragmatic Bookshelf? Sign up for our newsletter. You’ll be the first to know about author speaking engagements, books in beta, new books in print, and promo codes that give you discounts of up to 40%.

You have jobs coming in, and you need to execute them in order of priority. After doing some research, you decide to use Python’s built-in heapq module.

As usual, you start small and try out your code. Here’s the first try:

But, when you run the code, you get an interesting error:

What is going on?

In order to create an ordered heap, the heapq module needs to compare the inserted values. In your case, the values are named tuples (namedtuple), which is a subclass of the built-in…

--

--