← Data Structures
15 / 25
Lesson 15 — Heap / priority
Priority queue: most urgent first
A priority queue always hands you the most important item next, not the oldest. Python's heapq keeps a list arranged as a heap, where the smallest item is always at position 0. Push tuples (priority, task): tuples compare by their first item, so priority 1 comes out before priority 3.
import heapq
h = []
heapq.heappush(h, (2, "email"))
heapq.heappush(h, (1, "fire!"))
heapq.heappop(h) # (1, 'fire!')
Why it matters: hospital triage, OS schedulers and Dijkstra's algorithm all need "give me the most urgent".
Want it another way?
Task
Push every (priority, task) onto the heap, then pop them all. Tasks should come out by priority.
Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.
Test your knowledge
A quick 3-question quiz on this lesson — instant feedback.