heapq: always the smallest first
🌍 In real life. In a hospital emergency room, patients aren't seen in the order they arrive. A nurse gives each one a priority (1 = most urgent), and the doctor always takes the most urgent patient next. New patients keep arriving, so the list changes all the time.
Sorting the whole list after every arrival would work, but it's wasteful. A heap is a list kept in a clever, half-sorted order where the smallest item is always at index 0. Step by step:
heapq.heappush(h, x)addsxand keeps the heap ruleheapq.heappop(h)takes out the smallest and keeps the heap rule- the rule: every parent is no bigger than its children, where the children of index
iare at2*i+1and2*i+2 - each push or pop only does a few swaps, even for a huge list
The idea in one sentence: a heap is a list arranged so the smallest item is always at index 0, and heapq.heappush/heappop add and remove items while keeping that true.
Its words:
- priority queue: always serve the most urgent (smallest) item next
heapq.heappush(h, x)/heapq.heappop(h): add, and take the smallestheapq.heapify(h): rearrange an existing list into a heap(priority, name)tuples: the priority decides the order
Watch the heap work. The same list is drawn twice: as a tree on top (index 0 is the root) and as the real list underneath. Red means urgent (small), blue means it can wait (big). A pushed number joins at the end and climbs while it's smaller than its parent. A pop takes the top to the tray, moves the last item up, and lets it sink below any smaller child.
import heapq
h = [5, 3, 8, 1]
heapq.heapify(h)
print(h)
heapq.heappush(h, 2)
print(h, "smallest:", h[0])
print([heapq.heappop(h) for _ in range(len(h))])Patients, not just numbers. Push a tuple (priority, name). Tuples compare by their first item, so the priority decides; for a tie, the second item (the name) decides. Don't push dicts: Python can't tell whether one dict is "smaller" than another and stops with a TypeError.
For the biggest first (a max-heap), push the negative: -score. And when you only want the top few, heapq.nsmallest(k, items) and heapq.nlargest(k, items) do it in one call.
import heapq
er = []
heapq.heappush(er, (3, "sprained ankle"))
heapq.heappush(er, (1, "heart attack"))
heapq.heappush(er, (2, "broken arm"))
heapq.heappush(er, (1, "bad allergy"))
while er:
priority, case = heapq.heappop(er)
print(priority, case)
scores = [72, 95, 88, 60, 91]
print(heapq.nlargest(3, scores))
print(heapq.nsmallest(2, scores))Why a heap instead of sorting? Sorting the whole list every time a patient arrives costs about n × log n each time. A push or pop only climbs or sinks one path of the tree, about log₂ n steps: for 1,000,000 items, about 20. That's why heaps run priority queues, Dijkstra's shortest paths (World 8) and "the k smallest" problems.
Mistakes and edge cases.
- Expecting a sorted list. After
heapify([5, 1, 3])the list is[1, 5, 3]: only index 0 is guaranteed to be the smallest. - heappop on a plain list. Popping from a list that was never heapified gives wrong answers, with no error. Call
heapifyfirst. - Items that can't be compared. Pushing dicts gives
TypeError: '<' not supported between instances of 'dict' and 'dict'; push(priority, name)tuples. - Wanting the largest. heapq is a min-heap; push
-priorityto get the largest first.
Quiz
What does this print?
import heapq h = [] for x in [5, 1, 4]: heapq.heappush(h, x) print(h[0])What does this print?
import heapq h = [3, 1, 2] heapq.heapify(h) print(heapq.heappop(h), heapq.heappop(h))After some pushes, what is promised about the heap list
h?- h[0] is the smallest item
- The whole list is sorted
- h[-1] is the biggest item
What does this print?
import heapq print(heapq.nlargest(2, [4, 9, 1, 7]))What does this print?
import heapq er = [] heapq.heappush(er, (2, "cut")) heapq.heappush(er, (1, "heart")) heapq.heappush(er, (3, "cold")) print(heapq.heappop(er)[1])This should print the smallest number, 1, but it prints 5. Which line is missing a step?
import heapq nums = [5, 1, 3] print(heapq.heappop(nums))
Coding tasks
Write
triage(patients: list[tuple[int, str]]) -> list[str]withheapq: the names in the order they're seen, smallest priority first (and by name for a tie).Write
cheapest(prices: dict[str, int], k: int) -> list[str]: the names of thekcheapest items, cheapest first, usingheapq.nsmallestwithkey=prices.get.Finish the class
Clinic.arrive(name, priority)adds a patient;next_patient()gives back the name of the most urgent one (smallest priority) and removes them, orNonewhen nobody is waiting. Patients with the same priority are seen in the order they arrived, not by name.