← Back to all snippets
PYTHON

Implement a Min-Heap (Priority Queue) with heapq

Utilize Python's `heapq` module to create and manage a min-heap, effectively implementing a priority queue for scheduling tasks or processing elements by priority.

import heapq

# Initialize an empty min-heap
min_heap = []

# Add elements to the heap (push)
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}") # Not necessarily sorted visually

# Get and remove the smallest element (pop)
smallest = heapq.heappop(min_heap)
print(f"Smallest element popped: {smallest}")
print(f"Heap after pop: {min_heap}")

# Get the smallest element without removing it (peek - requires specific implementation)
# The smallest element is always at index 0
if min_heap:
    print(f"Current smallest element (peek): {min_heap[0]}")

# Replace the smallest element with a new one
heapq.heapreplace(min_heap, 5) # Pops smallest (3), pushes 5
print(f"Heap after replace: {min_heap}")

# Building a heap from an existing list
my_list = [5, 2, 8, 0, 1]
heapq.heapify(my_list)
print(f"Heap from list: {my_list}")
How it works: This snippet demonstrates how to use Python's `heapq` module to implement a min-heap, which functions as a priority queue. A min-heap ensures that the smallest element is always at the root (index 0). `heappush` adds an element while maintaining the heap property, and `heappop` removes and returns the smallest element. `heapify` can convert an existing list into a heap in linear time, and `heapreplace` efficiently pops the smallest item and pushes a new one.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs