Skip to content
KALANBLON
Show contents

Chapter 4 of 7 · 20 min

Priority queues

By the end of this chapter, you'll be able to

  • Explain what a priority queue is
  • Use heapq to add and remove items in order of priority
  • Store (priority, arrival order, value) tuples in a heap
  • Find the k smallest or largest values without sorting everything

The priority queue

A priority queue is a queue where each item has a priority, and where you always remove the item with the highest priority, whenever it arrived.

You could keep a list and sort it after every arrival, but sorting costs O(n log n) each time. A heap does better: adding or removing an item costs only O(log n). With a million items, log₂(n) is about 20: around twenty operations instead of a million.

heapq: a heap inside a list

The heapq module from the standard library arranges the items of an ordinary list so that the smallest is always at position 0. It does not sort the whole list: it only guarantees that each item is smaller than its "children" in an imaginary tree, which is enough to take out the minimum quickly.

  • heapq.heappush(heap, x) adds x;
  • heapq.heappop(heap) removes and returns the smallest;
  • heap[0] looks at the smallest without removing it.
import heapq

heap = []
for number in [42, 7, 19, 3, 25]:
    heapq.heappush(heap, number)

print("smallest:", heap[0])
print(heapq.heappop(heap), heapq.heappop(heap), heapq.heappop(heap))
print("left:", sorted(heap))
smallest: 3
3 7 19
left: [25, 42]

Priorities with tuples

For the emergency room, we store tuples (priority, arrival order, patient). Python compares tuples item by item: first the priority (1 = most urgent), then, for equal priorities, the arrival order. The arrival number also guarantees that two patients with the same priority are never compared by name.

import heapq

emergencies = []
arrivals = [("Kofi", 3), ("Awa", 1), ("Lina", 2), ("Tariq", 1)]
for number, (patient, priority) in enumerate(arrivals):
    heapq.heappush(emergencies, (priority, number, patient))

while emergencies:
    priority, number, patient = heapq.heappop(emergencies)
    print(f"priority {priority}: {patient} (arrived in position {number + 1})")
priority 1: Awa (arrived in position 2)
priority 1: Tariq (arrived in position 4)
priority 2: Lina (arrived in position 3)
priority 3: Kofi (arrived in position 1)

Kofi arrived first, but his priority is the lowest: he goes last. Awa and Tariq have the same priority: Awa, who arrived earlier, goes first.

heappop takes out Awa; Lina becomes the most urgent. Kofi will wait.

Step 6 of 6
Text description of the animation
  1. Three patients arrive with a priority: 1 is the most urgent.
  2. The heap is an empty list.
  3. Kofi arrives first, with priority 3.
  4. Awa, more urgent, takes position 0: the smallest is always at the front.
  5. Lina (priority 2) slots in without displacing Awa.
  6. heappop takes out Awa; Lina becomes the most urgent. Kofi will wait.

The k largest without sorting everything

To get the top 3 sales among thousands, there is no need to sort everything: heapq.nlargest(k, data) and heapq.nsmallest(k, data) do it in O(n log k).

import heapq

sales = {"Awa": 120_000, "Kofi": 95_000, "Lina": 143_000, "Tariq": 88_000, "Mei": 131_000}
podium = heapq.nlargest(3, sales.items(), key=lambda pair: pair[1])
for rank, (seller, amount) in enumerate(podium, start=1):
    print(rank, seller, f"{amount:,} CFA francs")
1 Lina 143,000 CFA francs
2 Mei 131,000 CFA francs
3 Awa 120,000 CFA francs

Mini-lab: urgent tasksPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: merging sorted lists

Three branches each send the sorted list of their appointment times. Write merge(lists) that returns a single sorted list, using a heap that never holds more than one item per branch.

branches = [[8, 11, 15], [9, 10, 16], [7, 12]]
print(merge(branches))   # [7, 8, 9, 10, 11, 12, 15, 16]
Hint 1
Put the first item of each list in the heap, as (value, list number, position).
Hint 2
On each heappop, add the value to the result, then push the next item of the same list if there is one.
Show the solution and common mistakes
import heapq

def merge(lists):
    heap = [(l[0], i, 0) for i, l in enumerate(lists) if l]
    heapq.heapify(heap)
    result = []
    while heap:
        value, i, pos = heapq.heappop(heap)
        result.append(value)
        if pos + 1 < len(lists[i]):
            heapq.heappush(heap, (lists[i][pos + 1], i, pos + 1))
    return result

print(merge([[8, 11, 15], [9, 10, 16], [7, 12]]))
[7, 8, 9, 10, 11, 12, 15, 16]

heapify turns a list into a heap in O(n). The heap holds only one item per branch: each operation costs O(log k) for k branches. This is what the standard library's heapq.merge does.

Common mistakes:

  • Concatenating the lists then sorting: the result is correct, but you ignore the fact that they are already sorted.
  • Forgetting if l: a branch with no appointments would make l[0] crash with IndexError.
  • Not recording the list number and position: you would no longer know which item to push next.

Summary

  1. 1A priority queue always releases the highest-priority item, not the first one in.
  2. 2heapq keeps the smallest item at position 0: heappush and heappop cost O(log n).
  3. 3(priority, arrival order, value) tuples break ties without comparing the values.
  4. 4A heap is not a sorted list: only heap[0] is guaranteed.
  5. 5nlargest and nsmallest give the top k without sorting everything.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.