Schedule Work with Priority Queues and Heaps
Core idea
A priority queue removes the most urgent item rather than the oldest. Python 3.13 heapq is a min-heap: the smallest key is at index zero. heapify builds a heap in O(n); push and pop take O(log n) comparisons. Use a unique arrival counter after priority to make equal priorities FIFO and avoid comparing arbitrary payloads.
from heapq import heapify, heappopjobs = [(3, 'pack'), (1, 'inspect'), (2, 'label')]heapify(jobs)print(heappop(jobs)[1])print(heappop(jobs)[1])Smaller numeric priority means earlier processing.
Break ties by arrival
from heapq import heappush, heappopheap = []for i, label in enumerate(['Z', 'A']): heappush(heap, (1, i, {'label': label}))print(heappop(heap)[2]['label'])print(heappop(heap)[2]['label'])Unique counters avoid comparing dictionaries.
Common mistake
A heap list is not globally sorted. Changing a stored priority without restoring the heap invariant can break subsequent removals.
Practice
Schedule three jobs with priorities 2, 1, 1 and verify arrival order for the tie.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Priority queues and heaps
Check your understanding of priority queues and heaps.
What is printed?
from heapq import heapify,heappopa=[6,1,4]heapify(a)print(heappop(a))What is printed?
print(min((1,2,'A'),(1,1,'Z'))[2])Which index holds the minimum in a nonempty heap?
What is heapify time?