Always the Smallest First? Priority Queues with Python's heapq

This article explains how Python's heapq module keeps a list as a binary heap, builds a priority queue that handles ties and changing priorities, measures it against sorting, and describes the maximum-heap functions of Python 3.14.

A green tree python with white and yellow spots coiled in a heap over a branch, its head resting on top of the pile
Photo by JL on Unsplash

Many programs repeatedly need the smallest element of a changing collection: the next event of a simulation, the cheapest path to expand or the most urgent task. Sorting the whole collection after every change answers the question at a cost that grows with every insertion. The present article addresses the heapq module of the standard library, which maintains an ordinary list as a binary heap, so that the smallest element is always at index zero and insertions and removals take logarithmic time. It explains the heap invariant, builds a priority queue that survives equal priorities and changing tasks, measures the module against sorting, and describes the maximum-heap functions added in Python 3.14. Keeping only the order that matters, the position of the smallest element, instead of the order of the whole list, is the secret weapon of heapq.

A List That Keeps Its Smallest Element First

A heap is a list in which every element is less than or equal to its two children, stored at positions 2k + 1 and 2k + 2, which guarantees that heap[0] is the smallest element and says nothing about the order of the rest. The function heapify establishes this invariant in place and in linear time, heappush and heappop preserve it in logarithmic time, and heappushpop and heapreplace combine a push and a pop in a single, cheaper operation.

import heapq

numbers = [10, 2, 5, 1, 8]
heapq.heapify(numbers)
print(numbers)     # Output: [1, 2, 5, 10, 8]
print(numbers[0])  # Output: 1

heapq.heappush(numbers, 3)
print([heapq.heappop(numbers) for _ in range(3)])  # Output: [1, 2, 3]
print(heapq.heappushpop(numbers, 4))               # Output: 4
print(sorted(numbers))                             # Output: [5, 8, 10]

The printed heap is not sorted, because only the first position is guaranteed; successive calls to heappop, however, return the elements in ascending order. The call to heappushpop returns 4 at once, since the new value is smaller than every element already in the heap, which saves both a push and a pop. Unlike the double-ended queues described in the article devoted to deque, which serve elements in arrival order, a heap serves them in order of value, whatever the order in which they arrived.

A Priority Queue That Survives Ties and Changes

Online battle games keep a threat table for each enemy, which records how much danger every player represents, and the enemy always attacks whoever is at the top of that table. This means that a priority queue only needs to know its highest-priority entry at every moment, which is exactly what a heap guarantees, while the order of the remaining entries can stay partial. The analogy, however, stops at this point, because a threat table updates its values continuously, whereas an entry of a heap cannot change its priority in place: the documented technique marks the old entry as removed and pushes a new one. The following example applies that technique, and also adds a counter between priority and task, because two entries with equal priorities would otherwise be ordered by comparing the tasks themselves.

import heapq
import itertools

class TaskQueue:
    REMOVED = "<removed>"

    def __init__(self):
        self._heap, self._entries = [], {}
        self._counter = itertools.count()

    def add(self, task, priority):
        if task in self._entries:
            self._entries.pop(task)[-1] = self.REMOVED
        entry = [priority, next(self._counter), task]
        self._entries[task] = entry
        heapq.heappush(self._heap, entry)

    def pop(self):
        while self._heap:
            priority, _, task = heapq.heappop(self._heap)
            if task is not self.REMOVED:
                del self._entries[task]
                return task
        raise KeyError("pop from an empty queue")

queue = TaskQueue()
queue.add("write report", 2)
queue.add("fix outage", 1)
queue.add("reply email", 2)
queue.add("write report", 0)
print([queue.pop() for _ in range(3)])
# Output: ['write report', 'fix outage', 'reply email']

pending = []
try:
    heapq.heappush(pending, (1, {"id": 1}))
    heapq.heappush(pending, (1, {"id": 2}))
except TypeError as error:
    print(error)  # Output: '<' not supported between instances of 'dict' and 'dict'

The report moves to the front when its priority changes to zero, its old entry is skipped silently, and the two tasks with priority 2 leave in the order in which they were added, thanks to the counter. The last lines show the failure that the counter prevents: with equal priorities, the tuples fall back to comparing dictionaries, which do not support ordering. A data class declared with order=True, whose payload field uses compare=False, as described in the article devoted to data classes, is the alternative that the documentation also proposes.

Measuring the Heap Against Sorting

The advantage of a heap depends on how much of the order is actually needed, and the following measurement compares the module with sorting in the two cases that the documentation distinguishes.

import heapq
import random
import timeit

random.seed(1)
data = [random.random() for _ in range(200_000)]
few = timeit.timeit(lambda: heapq.nsmallest(10, data), number=3)
full = timeit.timeit(lambda: sorted(data)[:10], number=3)
many = timeit.timeit(lambda: heapq.nsmallest(100_000, data), number=3)
print(few < full, many > full)  # Output: True True

On CPython 3.12, with a million values instead of the 200,000 of the example, nsmallest(10) took about 18 milliseconds against about 458 for sorting the list, whereas nsmallest(100_000) took about 1.3 seconds, more than the complete sort; the documentation accordingly recommends sorted for large selections and min or max when only one element is needed. A priority queue of 20,000 values, filled and emptied with heappush and heappop, took about 0.025 seconds, against about 5.5 seconds for a list from which the minimum was found with min and removed with remove. When the data are searched rather than consumed, a sorted list with binary search, as examined in the article devoted to bisect, is the more appropriate structure.

Pitfalls of heapq

The module operates on plain lists and trusts its caller to keep the invariant, so most errors come from treating a heap as a sorted list or from modifying it behind the module's back. Six pitfalls are distinguished, which are the following:

  1. Expecting a sorted list. Only heap[0] is guaranteed; iterating over the list or indexing other positions gives no meaningful order.
  2. Breaking the invariant. Appending to the list, assigning an element or sorting part of it without calling heapify again silently corrupts the heap.
  3. Equal priorities. Tuples with equal priorities compare their next element, which raises TypeError for payloads such as dictionaries.
  4. Changing priorities in place. Modifying the priority of an entry already in the heap breaks the invariant; the entry must be marked as removed and pushed again.
  5. nsmallest with large n. For selections close to the size of the data, sorted is faster, and for a single element min or max is.
  6. Shared heaps between threads. The functions are not synchronized; queue.PriorityQueue adds the necessary locking.

Python 3.14 added public functions for maximum heaps, heapify_max, heappush_max, heappop_max, heappushpop_max and heapreplace_max; code that must also run on earlier versions continues to store negated priorities in an ordinary minimum heap.

Choosing a Structure for Ordered Access

Consequently, a heap is the right structure when the smallest or largest element is needed repeatedly while the collection changes, as the following table summarizes.

Situation Recommended approach
Repeatedly taking the smallest element of a changing collection heapq.heappush and heappop
The smallest or largest single element, once min or max
A few smallest or largest elements of a large collection heapq.nsmallest or nlargest
Most of the collection in order sorted
Searching sorted data without consuming it A sorted list with bisect
Elements served in arrival order collections.deque
A priority queue shared between threads queue.PriorityQueue
Largest element first, Python 3.14 or later The _max functions of heapq

Conclusion

It is concluded that heapq maintains a list as a binary heap whose first element is always the smallest, that it inserts and removes in logarithmic time and builds a heap in linear time, and that a priority queue needs a counter for ties and lazy removal for changing priorities. This magic serves partial order only: a heap is not a sorted list, large selections are faster with sorted, and the invariant holds only while every change goes through the module. Supplying a value for a missing key from inside a dictionary subclass, instead of checking for the key at every lookup, is the purpose of the special method __missing__, which is developed in a future article of this series.