How to Use heapq Module in Python for Priority Queues?

The heapq module in Python provides functions for implementing heaps based on regular lists. Heaps are binary trees for which every parent node has a value less than or equal to any of its children.

Importing heapq

import heapq

Creating a Heap

Initialize a list and convert it into a heap:

numbers = [5, 7, 9, 1, 3]
heapq.heapify(numbers)
print(numbers)  # Output: [1, 3, 9, 7, 5]

Adding Elements

Use heappush() to add elements:

heapq.heappush(numbers, 2)
print(numbers)  # Output: [1, 2, 9, 7, 5, 3]

Removing Elements

Use heappop() to remove the smallest element:

smallest = heapq.heappop(numbers)
print(smallest)  # Output: 1

Finding N Largest or Smallest Elements

Use nlargest() and nsmallest() functions:

largest = heapq.nlargest(2, numbers)
smallest = heapq.nsmallest(2, numbers)

Conclusion

The heapq module is efficient for implementing priority queues and heaps in Python. It provides a simple interface for heap operations.

Leave a Reply

Your email address will not be published. Required fields are marked *