Heaps and Priority Queues

Push tasks with priorities and always get the most urgent one first, using Python's heapq.

Python · intermediate · 5 min · 8 steps · free

What you'll learn

heap.py

import heapq

tasks = []
heapq.heappush(tasks, (3, 'write tests'))
heapq.heappush(tasks, (1, 'fix bug'))
heapq.heappush(tasks, (2, 'review'))
first = heapq.heappop(tasks)
second = heapq.heappop(tasks)
print(first, second, tasks)

Step by step

  1. This brings in Python's built-in heapq module, so the program can use the functions it provides.
  2. tasks is created and points to a new list: [].
  3. (3, "write tests") goes into the heap.
  4. (1, "fix bug") has a smaller priority, so heappush moves it to the front.
  5. a tuple is added to the end of the list that tasks points to.
  6. heappop always returns the smallest: priority 1.
  7. second is created and points to a new tuple: [2, 'review']. a tuple is removed from the start of the list that tasks points to.
  8. It prints (1, 'fix bug') (2, 'review') [(3, 'write tests')].

Common mistakes

Best practices

Key takeaways

Check yourself

tasks[0] is always?

Answer: The smallest item

Get the largest instead?

Answer: Push negative priorities

·

More in Trees and Heaps