PYTHON

Managing Priority Queues with heapq

Learn how to use Python's `heapq` module to implement a min-priority queue, essential for task scheduling or retrieving elements in order of priority in web applications.

import heapq

# Create an empty min-heap
min_heap = []

# Add elements to the heap
heapq.heappush(min_heap, 3) # (priority, item) can be used for custom sorting
heapq.heappush(min_heap, 1)
heapq.heappush(min_heap, 5)
heapq.heappush(min_heap, 2)
heapq.heappush(min_heap, 4)

print(f"Heap after pushes (internal representation, not sorted): {min_heap}")

# Pop elements (always returns the smallest element)
print(f"Popped element: {heapq.heappop(min_heap)}") # Output: 1
print(f"Popped element: {heapq.heappop(min_heap)}") # Output: 2

print(f"Heap after pops: {min_heap}")

# Get the smallest element without removing it
if min_heap:
    print(f"Smallest element (peek): {min_heap[0]}") # Output: 3

# Heapify an existing list (in-place operation)
initial_list = [7, 0, 9, 2, 4]
heapq.heapify(initial_list)
print(f"Heapified list: {initial_list}")
print(f"Popped from heapified: {heapq.heappop(initial_list)}") # Output: 0
How it works: The `heapq` module provides an implementation of the heap queue algorithm, commonly known as a priority queue. It allows you to efficiently add elements (`heappush`) and retrieve the smallest element (`heappop`) in logarithmic time (O(log n)). This data structure is invaluable in web development for scenarios such as task scheduling, event processing, finding the k-smallest/largest elements, or implementing custom priority-based workflows where you need quick access to the highest-priority item.

Need help integrating this into your project?

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

Hire DigitalCodeLabs