Use a negative priority instead, no need to subtract from sys.maxint.
queue.put((-priority, item))
An item with priority -10 will be returned before items with priority -5, for example.
Answer from Martijn Pieters on Stack OverflowPython
docs.python.org โบ 3 โบ library โบ heapq.html
heapq โ Heap queue algorithm
def running_median(iterable): "Yields the cumulative median of values seen so far." lo = [] # max-heap hi = [] # min-heap (same size as or one smaller than lo) for x in iterable: if len(lo) == len(hi): heappush_max(lo, heappushpop(hi, x)) yield lo[0] else: heappush(hi, heappushpop_max(lo, x)) yield (lo[0] + hi[0]) / 2 ยท For example: >>> list(running_median([5.0, 9.0, 4.0, 12.0, 8.0, 9.0])) [5.0, 7.0, 5.0, 7.0, 8.0, 8.5] A priority queue is common use for a heap, and it presents several implementation challenges: Sort stability: how do you get two tasks with equal priorities to be returned in the order they were originally added?
Top answer 1 of 2
47
Use a negative priority instead, no need to subtract from sys.maxint.
queue.put((-priority, item))
An item with priority -10 will be returned before items with priority -5, for example.
2 of 2
10
You can extend the Priority Queue to keep the logic unchanged:
from Queue import PriorityQueue
class DualPriorityQueue(PriorityQueue):
def __init__(self, maxPQ=False):
PriorityQueue.__init__(self)
self.reverse = -1 if maxPQ else 1
def put(self, priority, data):
PriorityQueue.put(self, (self.reverse * priority, data))
def get(self, *args, **kwargs):
priority, data = PriorityQueue.get(self, *args, **kwargs)
return self.reverse * priority, data
minQ = DualPriorityQueue()
maxQ = DualPriorityQueue(maxPQ=True)
minQ.put(10, 'A')
minQ.put(100, 'A')
maxQ.put(10, 'A')
maxQ.put(100,'A')
print "Min DQ: {}".format(minQ.get())
print "Max DQ: {}".format(maxQ.get())
Output:
Min DQ: (10, 'A')
Max DQ: (100, 'A')
Videos
22:35
DSA in Python - Introduction to Priority Queues using Binary Heaps ...
24:08
Heaps & Priority Queues - Heapify, Heap Sort, Heapq Library - DSA ...
15:57
Heaps & Priority Queues in Python - YouTube
15:57
Heaps & Priority Queues in Python
09:44
Maximize Efficiency with this Priority Queue Class in Python - YouTube
DigitalOcean
digitalocean.com โบ community โบ tutorials โบ priority-queue-python
How to Use a Priority Queue in Python | DigitalOcean
July 11, 2025 - This tutorial has covered the implementation of a priority queue in Python using both heapq and queue.PriorityQueue. Additionally, it has explored the creation of a max-heap using these modules.
Medium
medium.com โบ @huawei.zhu โบ built-in-stack-queue-and-priority-queue-in-python-e44a6cbf3771
Built-in stack, queue and priority queue in Python | by Huawei Zhu | Medium
September 2, 2025 - Using queue.PriorityQueue: This approach supports concurrent processes and itโs a class interface. The 2nd one โ heapq, is preferred. ... import heapq # also a built-in module in python, and this is min-heap. # To create a max-heap, # just make every item the opposite sign when you push them into the heap #======================== # Test 1: heapify a list #======================== a = [3, 5, 1, 2, 6, 8, 7] heapq.heapify(a) # this turns the list to a priority queue print("a =", a) # note the difference between a and a after heapify() #======================== # Test 2: initialize with an em
APXML
apxml.com โบ courses โบ advanced-python-programming-ml โบ chapter-4-advanced-data-structures-algorithms-ml โบ priority-queues-heaps
Python Priority Queues & Heaps in ML
In some filter-based feature selection methods, features are assigned scores based on criteria like mutual information or correlation with the target variable. A priority queue (e.g., a max-heap implemented using heapq.nlargest) can be used to efficiently find the top
Top answer 1 of 5
7
PriorityQueue by default only support minheaps.
One way to implement max_heaps with it, could be,
from queue import PriorityQueue
# Max Heap
class MaxHeapElement:
def __init__(self, x):
self.x = x
def __lt__(self, other):
return self.x > other.x
def __str__(self):
return str(self.x)
max_heap = PriorityQueue()
max_heap.put(MaxHeapElement(10))
max_heap.put(MaxHeapElement(20))
max_heap.put(MaxHeapElement(15))
max_heap.put(MaxHeapElement(12))
max_heap.put(MaxHeapElement(27))
while not max_heap.empty():
print(max_heap.get())
2 of 5
2
Based on the comments, the simplest way to get maxHeap is to insert negative of the element.
from queue import PriorityQueue
max_heap = PriorityQueue()
max_heap.put(MaxHeapElement(-10))
max_heap.put(MaxHeapElement(-20))
max_heap.put(MaxHeapElement(-15))
max_heap.put(MaxHeapElement(-12))
max_heap.put(MaxHeapElement(-27))
while not max_heap.empty():
print(-1*max_heap.get())
VisuAlgo
visualgo.net โบ en โบ heap
Binary Heap (Priority Queue) - VisuAlgo
C++ STL priority_queue (the default is a Max Priority Queue) and ยท Java PriorityQueue (the default is a Min Priority Queue). However, the built-in implementation may not be suitable to do some PQ extended operations efficiently (details omitted for pedagogical reason in a certain NUS course). Python heapq exists but its performance is rather slow.
Real Python
realpython.com โบ queue-in-python
Python Stacks, Queues, and Priority Queues in Practice โ Real Python
December 1, 2023 - Alternatively, you could ignore the element order until removing one with the highest priority, which you could find using the linear search algorithm. Looking up an element in an unordered list has O(n) time complexity. Sorting the entire queue would be even more expensive, especially when exercised often. Pythonโs list.sort() method employs an algorithm called Timsort, which has O(n log(n)) worst-case time complexity.
Faun
faun.pub โบ priority-queue-using-heapq-9d8fccc49d51
Priority Queue โ Python
April 28, 2025 - Since we know that we are interested in the middle elements to find the median. We create two heaps. One heap as min-heap and another one as max-heap. This way we are able to keep track of the middle elements in sorted order.
Squash
squash.io โบ python-priority-queue-a-practical-guide
Python Priority Queue Tutorial
September 13, 2024 - In a max heap, for every node i other than the root, the value of heap[i] is greater than or equal to the values of its children. In a min heap, the value of heap[i] is less than or equal to the values of its children. Binary heaps are an efficient data structure for implementing priority queues because they allow for efficient insertion and removal of elements based on their priority.
HowToDoInJava
howtodoinjava.com โบ home โบ python datatypes โบ python priority queue using queue, heapq and bisect modules
Python Priority Queue using queue, heapq and bisect Modules
March 6, 2024 - The heapq module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm. Heaps are binary trees for which every parent node has a value less than or equal to any of its children, the smallest element is always the root, heap[0]. We use the following methods to push and pop the queue elements: heappush(): pushes the value item onto the heap, maintaining the heap invariant. heappop(): pops and returns the smallest item from the heap, maintaining the heap invariant. The following Python program uses the heapq module to implement a simple priority queue: