Sub topic 12
When FIFO Is Not Enough: Priority Queues
This chapter assumes you know the FIFO queue operations (enqueue, dequeue), basic Big-O notation, and Python tuples and comparison. It also assumes you have seen collections.deque and queue.Queue in earlier chapters.
Arrival order versus importance
A FIFO queue serves items in the order they arrived. That is correct for a line of print jobs, but not for an operating system scheduler or an alert system. A page about a production outage should not wait behind 500 routine emails.
A priority queue is an abstract data type that removes the item with the highest priority first. Arrival order matters only as a tie-breaker, if at all. The interface is similar to a queue: push (insert with a priority) and pop (remove the best item). The ordering rule is the difference.
Python's priority queue is built on a binary heap. A binary heap is an array arranged as a tree, where each parent is less than or equal to its children. The smallest item is always at index 0. Python's heapq module implements a min-heap, so "highest priority" means "smallest value".
Using heapq
heapq works on an ordinary list. heappush and heappop keep the heap property, and each takes O(log n) time.
import heapq
heap = []
heapq.heappush(heap, (2, "write report"))
heapq.heappush(heap, (1, "fix outage"))
heapq.heappush(heap, (3, "water plants"))
print(heap[0]) # (1, 'fix outage') peek is O(1)
while heap:
priority, task = heapq.heappop(heap)
print(priority, task)
# 1 fix outage
# 2 write report
# 3 water plantsEach entry is a tuple. Python compares tuples element by element, so the priority decides the order.
Ties and the counter trick
Tuple comparison has a catch. If two entries have equal priorities, Python compares the next elements. If those are dictionaries or custom objects, the comparison raises TypeError. Even when it works, equal-priority items do not come out in insertion order.
The usual fix is to put a unique, increasing counter between the priority and the payload. The counter is never equal, so the payload is never compared. It also makes ties FIFO.
import heapq
import itertools
heap = []
counter = itertools.count()
def push(priority, task):
heapq.heappush(heap, (priority, next(counter), task))
push(2, {"name": "email"})
push(1, {"name": "fix outage"})
push(2, {"name": "report"})
push(1, {"name": "page on-call"})
while heap:
priority, _, task = heapq.heappop(heap)
print(priority, task["name"])
# 1 fix outage
# 1 page on-call
# 2 email
# 2 reportWithout the counter, this program would fail on the first tie, because dictionaries cannot be ordered.
Max-priority and thread safety
To get the largest value first, store the negated priority, for example (-score, next(counter), item). Remember to negate it again when you read it back.
heapq is not thread-safe. For producer-consumer work across threads, use queue.PriorityQueue. It wraps a heap in the same locking and blocking behavior as queue.Queue, including put, get, task_done, and join. It also returns the lowest entry first.
import queue
pq = queue.PriorityQueue()
pq.put((2, "normal job"))
pq.put((1, "urgent job"))
print(pq.get()) # (1, 'urgent job')The same tie rule applies. Use (priority, counter, payload) tuples here as well.
Costs compared with a FIFO queue
| Operation | `deque` (FIFO) | `heapq` list (priority) |
|---|---|---|
| Insert | O(1) | O(log n) |
| Remove next item | O(1) | O(log n) |
| Peek next item | O(1) | O(1) |
| Remove an arbitrary item | O(n) | O(n) |
| Build from n items | O(n) | O(n) with `heapify` |
Priority ordering costs a logarithmic factor on each insert and removal. Do not pay it if arrival order is enough. A priority queue with every priority equal is a slower FIFO queue.
Common errors
- Treating the list as sorted. Only
heap[0]is guaranteed to be the smallest. Iterating or slicing the list does not give sorted order. Useheapq.nsmallestor pop repeatedly. - Mutating an entry in the heap. Changing a priority in place breaks the heap property. Instead, push a new entry and mark the old one as stale, then skip stale entries when you pop.
- Using
list.sort()after every insert. This costs O(n log n) per insert, where a heap costs O(log n). - Forgetting that the smallest value wins. A "priority 10" task runs after a "priority 1" task.
Exercise
You push the tuples (1, {"id": "a"}) and (1, {"id": "b"}) onto a heapq heap. What happens, and how do you fix it so that "a" is popped before "b"?
Show answer
The second push raises TypeError, because the priorities tie and Python then tries to compare two dicts, which cannot be ordered. Insert a counter from itertools.count() as the second tuple element, giving (1, 0, {"id": "a"}) and (1, 1, {"id": "b"}). The counter breaks the tie and makes equal priorities come out in insertion order.