In a normal queue the one who arrived first goes first. In a priority queue the one with the highest priority goes first, even if it arrived later: hospital emergencies, tasks in a scheduler, the routes of a GPS. Python offers it in the heapq module.
Heaps
heapq works with a list that is kept organised as a *min-heap*: the smallest element is always at position 0. Inserting and removing the minimum are fast operations, much faster than sorting the whole list each time.
import heapq
heap = []
heapq.heappush(heap, 5)
heapq.heappush(heap, 1)
heapq.heappush(heap, 3)
print(heap[0]) # 1 (peek at the minimum without removing it)
print(heapq.heappop(heap)) # 1
print(heapq.heappop(heap)) # 3
print(heapq.heappop(heap)) # 5
Note: the content of the list is not sorted, it only satisfies the heap property. If you want the values in order, pop them one by one with heappop.
Creating a heap at once
import heapq
data = [9, 4, 7, 1, 8]
heapq.heapify(data) # turns the list into a heap, in place
print(data[0]) # 1
print(heapq.nsmallest(2, [9, 4, 7, 1, 8])) # [1, 4]
print(heapq.nlargest(2, [9, 4, 7, 1, 8])) # [9, 8]
nsmallest and nlargest are ideal for getting the best *N* without sorting everything.
Priorities with tuples
To associate a task with its priority you store tuples: Python compares them element by element, so it sorts by priority first.
import heapq
queue = []
heapq.heappush(queue, (3, "report"))
heapq.heappush(queue, (1, "backup"))
heapq.heappush(queue, (2, "mail"))
while queue:
priority, task = heapq.heappop(queue)
print(priority, task)
# 1 backup
# 2 mail
# 3 report
Tie-breaking with a counter
If two tasks have the same priority, Python compares the next element of the tuple (the name), and if they are not comparable, it fails. The usual solution is to add an increasing counter as the second element, which also makes them be served in order of arrival.
import heapq
queue = []
counter = 0
for priority, name in [(2, "b"), (1, "z"), (2, "a")]:
heapq.heappush(queue, (priority, counter, name))
counter += 1
while queue:
priority, _, name = heapq.heappop(queue)
print(priority, name)
# 1 z
# 2 b (arrived before a)
# 2 a
It is the technique you need in Task priority queue.
A max-heap
heapq only offers a min-heap. To always get the largest, store the values with a negative sign.
import heapq
heap = []
for n in [4, 9, 2]:
heapq.heappush(heap, -n)
print(-heapq.heappop(heap)) # 9
print(-heapq.heappop(heap)) # 4
When to use each structure
| I need... | Use |
|---|---|
| Always take the last one that came in | Stack (list) |
| Serve in order of arrival | Queue (deque) |
| Always take the most urgent or the smallest | Priority queue (heapq) |
| Traverse a graph by layers | Queue (deque) |
| Traverse a graph to the end | Stack (list) |
With this lesson you have seen the classic structures: stacks, queues, linked lists, trees, graphs and heaps. Each one solves a type of problem well; choosing the right one is half of the work.