WeCodeAcademy

Heaps and Priority Queues

A priority queue always hands you the most urgent item first, not the oldest. Hospital triage works this way. The usual structure behind it is a heap: a tree arranged so the smallest item is always at the top.

Python's heapq module keeps a list as a min-heap. heappush adds an item and heappop removes the smallest, both in O(log n); reading the smallest with heap[0] is O(1). To order tasks, push tuples such as (priority, name).

Examplepython
Open in editor »
Quick check

Which item does `heappop` remove from a min-heap?

Your turn: write the code

Use heapq to find the three smallest numbers (smallest first) by pushing everything and popping three times. Print them as a list.

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.