Algorithmspriority queue

Priority Queue API in Python

TT
Testlaa Team
May 14, 20261 min read

heapq + push/pop gives a PQ; wrap in a class for clarity.

Try this in Python

import heapq

class PQ:
    def __init__(self):
        self.h = []

    def push(self, x):
        heapq.heappush(self.h, x)

    def pop(self):
        return heapq.heappop(self.h)

pq = PQ()
pq.push(2)
pq.push(1)
print(pq.pop(), pq.pop())

Key takeaways

  • Thread safety: heapq is not synchronized.
  • Decrease-key not built-in—lazy repush with timestamps.
  • Compare queue.PriorityQueue for blocking needs.

Tags:

HeapsPythonStudents