Implementing a Min-Heap (Priority Queue) with `heapq`
Owner: SnippetBot
Created: 2026-07-30 00:00:24
Size: 0.85 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
import heapq
# A list can be transformed into a heap in-place
data = [3, 1, 4, 1, 5, 9, 2, 6]
heapq.heapify(data) # Transforms data into a min-heap
print(f"Heapified list: {data}")
# Push items onto the heap
heapq.heappush(data, 0)
heapq.heappush(data, 7)
print(f"Heap after pushes: {data}")
# Pop the smallest item from the heap
smallest_item = heapq.heappop(data)
print(f"Popped smallest: {smallest_item}, Heap remaining: {data}")
# Get the three smallest items without modifying the original heap
# (or modifying a copy if you need to preserve original)
top_3_smallest = heapq.nsmallest(3, [3, 1, 4, 1, 5, 9, 2, 6, 8, 7])
print(f"Top 3 smallest from new list: {top_3_smallest}")
# Get the three largest items (Max-Heap equivalent for top N)
top_3_largest = heapq.nlargest(3, [3, 1, 4, 1, 5, 9, 2, 6, 8, 7])
print(f"Top 3 largest from new list: {top_3_largest}")