Python Basics: Taking the Next Item with heapq
A queue of jobs often needs the most urgent item next. Python’s heapq module maintains a heap in a list, with the smallest item at index zero.
Use Python 3.12 or newer on Linux. Each example runs independently, using only in-memory data.
Remove the smallest value
Save as demo_heapq_1.py:
import heapq
values = [8, 3, 5]
heapq.heapify(values)
heapq.heappush(values, 2)
print("Next:", values[0])
print("Removed:", heapq.heappop(values))
print("Remaining:", sorted(values))Run it from the directory where you saved it:
python3 demo_heapq_1.pyOutput:
Next: 2
Removed: 2
Remaining: [3, 5, 8]heapify() changes the original list. The whole heap is not necessarily sorted; sorted() above creates a separate display list. Use heap operations for updates, because ordinary append() can break the ordering rule. Popping an empty heap raises IndexError.
Keep equal-priority jobs in arrival order
Save as demo_heapq_2.py:
import heapq
from itertools import count
queue = []
sequence = count()
for priority, name in [(2, "report"), (1, "backup"), (1, "cleanup")]:
job = {"name": name}
heapq.heappush(queue, (priority, next(sequence), job))
while queue:
priority, order, job = heapq.heappop(queue)
print(priority, job["name"])Run it from the directory where you saved it:
python3 demo_heapq_2.pyOutput:
1 backup
1 cleanup
2 reportHere, smaller numbers mean higher urgency. Tuples compare from left to right. The unique sequence number preserves arrival order for ties and prevents Python from trying to order the dictionaries. Do not change a queued priority in place; the heap will not repair itself.
Pick a few results
Save as demo_heapq_3.py:
import heapq
durations = [14, 5, 21, 8, 3]
print("Shortest:", heapq.nsmallest(2, durations))
print("Longest:", heapq.nlargest(2, durations))
print("Original:", durations)Run it from the directory where you saved it:
python3 demo_heapq_3.pyOutput:
Shortest: [3, 5]
Longest: [21, 14]
Original: [14, 5, 21, 8, 3]These helpers accept ordinary iterables; there is no need to heapify first. They are useful when selecting a small number of results. For a complete ordered list, start with sorted(); for just one extreme, use min() or max().
References
Acknowledgements
This post was created with assistance from AI.