Sub topic 7
Using heapq in practice
This chapter assumes you know Python lists and tuples, the heap property, and the array layout with sift up and sift down. You have already built a MinHeap by hand. In production code you use the standard library module heapq instead.
What heapq is
heapq has no heap class. It is a set of functions that treat an ordinary Python list as a binary min-heap. The list layout is the one you already know: the children of index i sit at 2*i + 1 and 2*i + 2, and heap[0] is the smallest item.
| Function | What it does | Cost |
|---|---|---|
| `heapify(x)` | Rearranges a list into a heap in place | O(n) |
| `heappush(h, item)` | Adds an item (sift up) | O(log n) |
| `heappop(h)` | Removes and returns the smallest item (sift down) | O(log n) |
| `heapreplace(h, item)` | Pops the smallest, then pushes the new item | O(log n) |
| `heappushpop(h, item)` | Pushes, then pops the smallest | O(log n) |
| `h[0]` | Peeks at the smallest item | O(1) |
heapreplace pops first, so it can return an item smaller than the one you pass in. heappushpop pushes first, so it never returns something larger than the item you pass in. Both are faster than doing the push and pop as two separate calls.
A first session
import heapq
nums = [5, 1, 8, 3]
heapq.heapify(nums) # O(n), in place
heapq.heappush(nums, 2)
print(nums[0]) # 1, peek without removing
print(heapq.heappop(nums)) # 1
print(heapq.heappop(nums)) # 2After heapify, the list is in heap order, not sorted order. Only nums[0] is guaranteed to be the minimum, so printing the whole list shows a layout that looks scrambled.
Max-heaps by negation
heapq only offers a min-heap. For numbers, store the negated value and negate it again on the way out.
import heapq
max_heap = []
for x in [5, 1, 8, 3]:
heapq.heappush(max_heap, -x)
print(-heapq.heappop(max_heap)) # 8For non-numeric keys, wrap the priority in a tuple with a negated or inverted sort key instead.
Tuples as priorities
Python compares tuples element by element. A tuple (priority, payload) therefore orders by priority first. When two priorities are equal, Python compares the payloads, which can be slow, can be meaningless, or can raise TypeError if the payload type has no ordering (a dict, for example).
The fix is a counter as a middle element. It is unique and increasing, so the comparison never reaches the payload, and equal priorities come out in insertion order.
import heapq
from itertools import count
tie = count()
tasks = []
heapq.heappush(tasks, (2, next(tie), "write report"))
heapq.heappush(tasks, (1, next(tie), "fix outage"))
heapq.heappush(tasks, (1, next(tie), "reply to email"))
while tasks:
priority, _, name = heapq.heappop(tasks)
print(priority, name)This prints fix outage before reply to email, because both have priority 1 and the first was pushed earlier. write report comes last.
Common errors
- Using a plain list operation on a heap.
list.append,list.sort,list.removeandlist.pop()do not keep the heap property. Use theheapqfunctions. - Calling
heappopon an empty list. It raisesIndexError. Checkif heap:first. - Forgetting that the module is min-only. Newer Python versions add max-heap helpers, but negation works everywhere.
- Pushing equal priorities with unorderable payloads. Add a counter, as shown above.
- Mutating an item already in the heap. If its priority changes, the heap does not know. Push a new entry instead, a technique covered later with Dijkstra's algorithm.
Exercise
You push the tuples (1, {"job": "a"}) and (1, {"job": "b"}) onto a heap with heappush. What happens, and how do you fix it?
Show answer
The second push compares the tuples. The priorities tie at 1, so Python compares the dicts, and dicts do not support "<", so a TypeError is raised. Insert a unique counter as the second element, for example (1, next(tie), {"job": "b"}), so the comparison is always decided before it reaches the dict. This also keeps equal priorities in insertion order.
Exercise
Using only heapq, how do you get the largest of the numbers [4, 9, 2] out of a heap in O(log n)?
Show answer
Push the negated values (-4, -9, -2) with heappush. Then heappop returns -9, and negating it gives 9.