Back to The Haunt
The craft3 min read

heapq only pops the smallest. Here is the largest.

Python's heapq module is a min-heap: heappop always returns the smallest item, and heap[0] is always the smallest. There is no flag to reverse it on Python 3.13 or older. The standard trick is to store negated values and flip the sign back when you read them.

Negate the numbers

import heapq
scores = [5, 1, 8, 3]
heap = [-s for s in scores]      # negate every value
heapq.heapify(heap)
print(-heap[0])                  # peek: 8
print(-heapq.heappop(heap))      # 8
print(-heapq.heappop(heap))      # 5
print(heapq.nlargest(2, scores)) # [8, 5]

heapify takes O(n) time, each push and pop takes O(log n), and peeking at heap[0] is O(1). If you only need the largest k items once, heapq.nlargest(k, items) is simpler than keeping a heap.

Priorities with items: add a tie-breaker

Most real heaps hold (priority, item) pairs. Tuples compare field by field, so when two priorities are equal, Python goes on to compare the items. If the items are dicts or your own objects, that raises TypeError.

The fix is a counter between the priority and the item, so a tie is settled before the items are ever compared:

import heapq
from itertools import count
jobs = [(2, {"name": "write"}), (1, {"name": "test"}), (2, {"name": "review"})]
heap = []
order = count()
for priority, job in jobs:
    heapq.heappush(heap, (-priority, next(order), job))
while heap:
    neg, _, job = heapq.heappop(heap)
    print(-neg, job["name"])
# 2 write
# 2 review
# 1 test

The highest priority comes out first, and equal priorities come out in the order they were pushed. Without the counter, heapq.heapify([(-p, job) for p, job in jobs]) fails as soon as it compares the two priority-2 jobs.

Python 3.14 and newer

Python 3.14 added max-heap functions to heapq, including heapify_max, heappush_max and heappop_max. If every machine and judge you use runs 3.14, they save the negation. Negation still works on every version, which matters on coding platforms that run an older Python.

Mistakes to check for

  • Reading `heap[-1]` as the largest. A min-heap is not sorted. After heapify([1, 5, 2, 9, 6, 3]) the last element is 3, not 9.
  • Forgetting to negate on the way out, so the answer comes back as -8.
  • Negating something that is not a number. You cannot negate a string. Push a small wrapper class whose __lt__ compares in reverse, or sort by a numeric key instead.
  • Pushing without the counter and finding the TypeError only when two priorities first tie.

Chapter 10 of our free Python for DSA book writes a min-heap by hand before it switches to heapq, so you can see what heappush and heappop actually do. The DSA hub has the same chapter in four more languages.

That’s it. Come back soon; the ghost keeps writing.Follow by RSS

Read next.