← Back to all snippets
PYTHON

Implement a Priority Queue with Python's `heapq` Module

Learn to create a priority queue in Python using the `heapq` module, essential for tasks like scheduling and graph algorithms where element priority matters for processing.

import heapq

# A min-heap implementation, elements with lower priority value are retrieved first.
# For max-heap, store items with negated priority.

priority_queue = [] # This list will be treated as a heap

# Add items to the priority queue: (priority, item)
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, (4, 'Task D'))
heapq.heappush(priority_queue, (1, 'Task A-prime')) # Same priority, insertion order might differentiate

print(f"Initial priority queue: {priority_queue}")

# Retrieve items by priority (lowest priority value first)
print(f"Processing items from priority queue:")
while priority_queue:
    priority, item = heapq.heappop(priority_queue)
    print(f"  Processing: {item} (Priority: {priority})")
How it works: Python's `heapq` module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm. It allows you to add elements and efficiently retrieve the smallest element (in a min-heap) without sorting the entire list. `heapq.heappush` adds an item while maintaining the heap invariant, and `heapq.heappop` removes and returns the smallest item. This snippet demonstrates how to use `heapq` to manage tasks based on their assigned priority, ensuring higher-priority tasks are processed first.

Need help integrating this into your project?

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

Hire DigitalCodeLabs