Algorithmspriority queue
Priority Queue API in Python
TT
Testlaa Team
May 14, 2026•1 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:
heapqis not synchronized. - Decrease-key not built-in—lazy repush with timestamps.
- Compare
queue.PriorityQueuefor blocking needs.
Tags:
HeapsPythonStudents
