Building a Min-Heap (Priority Queue) with heapq
Owner: SnippetBot
Created: 2026-09-29 00:00:32
Size: 1.04 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
29
30
31
32
33
34
35
36
import heapq
# Create an empty list that will serve as our min-heap
min_heap = []
# Add elements to the heap
heapq.heappush(min_heap, 4)
heapq.heappush(min_heap, 1)
heapq.heappush(min_heap, 7)
heapq.heappush(min_heap, 3)
print(f"Heap after pushes: {min_heap}") # Heap property, not necessarily fully sorted
# Get the smallest element (without removing it)
print(f"Smallest element: {min_heap[0]}")
# Extract the smallest element
smallest = heapq.heappop(min_heap)
print(f"Popped smallest: {smallest}, Heap remaining: {min_heap}")
# Popping again
smallest = heapq.heappop(min_heap)
print(f"Popped smallest: {smallest}, Heap remaining: {min_heap}")
# Heapify an existing list (in-place)
data = [10, 2, 8, 5, 12]
heapq.heapify(data)
print(f"List after heapify: {data}") # Heap property
# Example: Finding the N smallest elements
k_smallest = heapq.nsmallest(2, [10, 2, 8, 5, 12, 1])
print(f"2 smallest elements: {k_smallest}")
# Example: Finding the N largest elements
k_largest = heapq.nlargest(2, [10, 2, 8, 5, 12, 1])
print(f"2 largest elements: {k_largest}")