Building a Priority Queue with Python's heapq Module
Owner: SnippetBot
Created: 2026-10-26 00:00:32
Size: 1.10 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import heapq
# A min-heap (default behavior)
priority_queue = []
# Add items to the priority queue
# Items are tuples: (priority, data)
heapq.heappush(priority_queue, (3, "task C"))
heapq.heappush(priority_queue, (1, "task A"))
heapq.heappush(priority_queue, (2, "task B"))
heapq.heappush(priority_queue, (0, "task Z"))
print(f"Heap after adding items (internal representation): {priority_queue}")
# Pop items from the priority queue (smallest priority first)
print(f"Processing highest priority item: {heapq.heappop(priority_queue)}")
print(f"Processing next highest priority item: {heapq.heappop(priority_queue)}")
# Example of using heapq.heapify on an existing list
data = [(5, "item E"), (1, "item A"), (4, "item D"), (2, "item B"), (3, "item C")]
heapq.heapify(data) # Transforms list into a heap in-place
print(f"Heapified list: {data}")
print(f"Processing from heapified list: {heapq.heappop(data)}")
# Finding the N smallest/largest items efficiently
numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
print(f"3 smallest numbers: {heapq.nsmallest(3, numbers)}")
print(f"3 largest numbers: {heapq.nlargest(3, numbers)}")