You can use Queue.PriorityQueue.

Recall that Python isn't strongly typed, so you can save anything you like: just make a tuple of (priority, thing) and you're set.

Answer from Charlie Martin on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › priority-queue-using-queue-and-heapdict-module-in-python
Priority Queue using Queue and Heapdict module in Python - GeeksforGeeks
January 8, 2026 - A Priority Queue is a special type of queue where elements with higher priority are dequeued before elements with lower priority.
🌐
Stackify
stackify.com › a-guide-to-python-priority-queue
A Guide to Python Priority Queue - Stackify
February 18, 2025 - The push() method adds a new element with a specified priority to the heap. The pop() method removes and returns the element with the highest priority. The peek() method allows us to view ...
🌐
Python
docs.python.org › 3 › library › queue.html
queue — A synchronized queue class
In a LIFO queue, the most recently added entry is the first retrieved (operating like a stack). With a priority queue, the entries are kept sorted (using the heapq module) and the lowest valued entry is retrieved first.
🌐
Built In
builtin.com › data-science › priority-queues-in-python
Introduction to Priority Queues in Python | Built In
It can be implemented using lists, the heapq module for efficiency, or the thread-safe PriorityQueue class for concurrent applications. more A priority queue in Python allows elements to be processed based on assigned priority rather than arrival ...
🌐
Hostman
hostman.com › tutorials › implementing-a-priority-queue-in-python
Implementing a Priority Queue in Python: A Comprehensive Guide
Learn how to implement and use priority queues in Python with this guide. Discover code examples using `heapq` and `queue.PriorityQueue`.
🌐
DigitalOcean
digitalocean.com › community › tutorials › priority-queue-python
How to Use a Priority Queue in Python | DigitalOcean
July 11, 2025 - Before you start, make sure you ... with the highest priority (or lowest, for min-heap) is removed first. Python ships two ready-made solutions: heapq and queue.PriorityQueue....
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › priority-queue-in-python
Priority Queue in Python - GeeksforGeeks
April 26, 2025 - A priority queue is like a regular queue, but each item has a priority. Instead of being served in the order they arrive, items with higher priority are served first.
🌐
Medium
medium.com › @kapilsharmax24 › what-is-a-priority-queue-21badf357301
What is a Priority Queue ?. A priority queue is a special type of… | by Shivam | Medium
September 21, 2024 - The push method adds an item to the queue with a given priority. The pop method removes and returns the highest-priority item. ... Negative Priorities: In our implementation, we use negative priorities because Python’s heapq module treats ...
🌐
Python
docs.python.org › 3 › library › heapq.html
heapq — Heap queue algorithm
Raise KeyError if not found.' entry = entry_finder.pop(task) entry[-1] = REMOVED def pop_task(): 'Remove and return the lowest priority task. Raise KeyError if empty.' while pq: priority, count, task = heappop(pq) if task is not REMOVED: del entry_finder[task] return task raise KeyError('pop from an empty priority queue')
🌐
Medium
stephanekp.medium.com › priority-queues-from-scratch-for-dummies-in-under-5-minutes-c3d74468213f
Priority Queues. From scratch. For Dummies. In under 5 Minutes. | by Stephane K. | Medium
July 6, 2022 - What heapsort above does is use the priority queue to extract the max and rebuild the heap so all its elements abide by the heap property. Now you could build a proper API for it (with insert, find, delete, peek,…), but for my use case and given the time I had, heapify is already doing most of the work. I just need to use it and be clever about it. Now I was able to look up this pesky import. And imagine what? As I should have expected from the zen of python, it’s as simple as from queue import PriorityQueue.
Top answer
1 of 3
33

There is no such thing as a "most efficient priority queue implementation" in any language.

A priority queue is all about trade-offs. See http://en.wikipedia.org/wiki/Priority_queue

You should choose one of these two, based on how you plan to use it:

  • O(log(N)) insertion time and O(1) (findMin+deleteMin)* time, or
  • O(1) insertion time and O(log(N)) (findMin+deleteMin)* time

(* sidenote: the findMin time of most queues is almost always O(1), so here I mostly mean the deleteMin time can either be O(1) quick if the insertion time is O(log(N)) slow, or the deleteMin time must be O(log(N)) slow if the insertion time is O(1) fast. One should note that both may also be unnecessarily slow like with binary-tree based priority queues.)

In the latter case, you can choose to implement a priority queue with a Fibonacci heap: http://en.wikipedia.org/wiki/Heap_(data_structure)#Comparison_of_theoretic_bounds_for_variants (as you can see, heapq which is basically a binary tree, must necessarily have O(log(N)) for both insertion and findMin+deleteMin)

If you are dealing with data with special properties (such as bounded data), then you can achieve O(1) insertion and O(1) findMin+deleteMin time. You can only do this with certain kinds of data because otherwise you could abuse your priority queue to violate the O(N log(N)) bound on sorting. vEB trees kind of fall under a similar category, since you have a maximum set size (O(log(log(M)) is not referring to the number of elements, but the maximum number of elements) and thus you cannot circumvent the theoretical O(N log(N)) general-purpose comparison-sorting bound.

To implement any queue in any language, all you need is to define the insert(value) and extractMin() -> value operations. This generally just involves a minimal wrapping of the underlying heap; see http://en.wikipedia.org/wiki/Fibonacci_heap to implement your own, or use an off-the-shelf library of a similar heap like a Pairing Heap (a Google search revealed http://svn.python.org/projects/sandbox/trunk/collections/pairing_heap.py )


If you only care about which of the two you referenced are more efficient (the heapq-based code from http://docs.python.org/library/heapq.html#priority-queue-implementation-notes which you included above, versus Queue.PriorityQueue), then:

There doesn't seem to be any easily-findable discussion on the web as to what Queue.PriorityQueue is actually doing; you would have to source dive into the code, which is linked to from the help documentation: http://hg.python.org/cpython/file/2.7/Lib/Queue.py

   224     def _put(self, item, heappush=heapq.heappush):
   225         heappush(self.queue, item)
   226 
   227     def _get(self, heappop=heapq.heappop):
   228         return heappop(self.queue)

As we can see, Queue.PriorityQueue is also using heapq as an underlying mechanism. Therefore they are equally bad (asymptotically speaking). Queue.PriorityQueue may allow for parallel queries, so I would wager that it might have a very slightly constant-factor more of overhead. But because you know the underlying implementation (and asymptotic behavior) must be the same, the simplest way would simply be to run them on the same large dataset.

(Do note that Queue.PriorityQueue does not seem to have a way to remove entries, while heapq does. However this is a double-edged sword: Good priority queue implementations might possibly allow you to delete elements in O(1) or O(log(N)) time, but if you use the remove_task function you mention, and let those zombie tasks accumulate in your queue because you aren't extracting them off the min, then you will see asymptotic slowdown which you wouldn't otherwise see. Of course, you couldn't do this with Queue.PriorityQueue in the first place, so no comparison can be made here.)

2 of 3
29

The version in the Queue module is implemented using the heapq module, so they have equal efficiency for the underlying heap operations.

That said, the Queue version is slower because it adds locks, encapsulation, and a nice object oriented API.

The priority queue suggestions shown in the heapq docs are meant to show how to add additional capabilities to a priority queue (such as sort stability and the ability to change the priority of a previously enqueued task). If you don't need those capabilities, then the basic heappush and heappop functions will give you the fastest performance.

🌐
The Python Coding Stack
thepythoncodingstack.com › the python coding stack › if you love queuing, will you also love priority queuing? • [club]
If You Love Queuing, Will You Also Love Priority Queuing? • [Club]
December 15, 2025 - We’ll use the list just as the structure to hold the data, but we’ll rely on another tool for the fun stuff. It’s time to import the heapq module, which is part of the Python standard library: ... This module contains the tools to create and manage a heap queue, which is also known as a priority queue.
🌐
GitHub
github.com › mjwestcott › priorityqueue
GitHub - mjwestcott/priorityqueue: A priority queue implementation in Python with a O(log n) remove method · GitHub
Usage: >>> from priorityqueue import MinHeapPriorityQueue >>> items = [4, 0, 1, 3, 2] >>> pq = MinHeapPriorityQueue(items) >>> pq.pop() 0 A priority queue accepts an optional key function. >>> items = ['yy', 'ttttttt', 'z', 'wwww', 'uuuuuu', 'vvvvv', 'xxx'] >>> pq = MinHeapPriorityQueue(items, key=len) >>> pq.pop() 'z' >>> pq.pop() 'yy' Internally, the queue is a list of tokens of type 'Locator', which contain the priority value, the item itself, and its current index in the heap.
Author   mjwestcott
🌐
Akamai
akamai.com › cloud › guides › python-priority-queue
What is the Python Priority Queue? | Linode Docs
June 17, 2022 - get: This removes and returns the highest priority item from the queue. Additional parameters can be supplied indicating whether Python should block waiting for an item and how long it must wait. The default for the block parameter is True, while timeout defaults to None. By default, a get request blocks waiting forever for the next item to arrive. maxsize: This method returns the maximum size of the queue.
🌐
UCI ICS
ics.uci.edu › ~pattis › common › modules › courselibdoc › priorityqueue.html
Python: module priorityqueue
Classes builtins.object PriorityQueue · class PriorityQueue(builtins.object) Implements a Priority Queue data type: values are removed according to the highest priority value first rule. Methods defined here: __add__(self, x)Overload syntax: pq = pq + x is the same as pq.add(x) __bool__(s...
Top answer
1 of 4
4

The implementation of Queue.PriorityQueue relies on heappush(), which doesn't provide a way to handle custom sorting.

You could subclass PriorityQueue and use a little hack to make this work without breaking functionnality:

from queue import PriorityQueue

class CustomPriorityQueue(PriorityQueue):
    def _put(self, item):
        return super()._put((self._get_priority(item), item))

    def _get(self):
        return super()._get()[1]


    def _get_priority(self, item):
        return item[1]

Test run:

>>> q = CustomPriorityQueue(100)
>>> q.put((2, 3, 5))
>>> q.put((2, 5, 5))
>>> q.put((2, 1, 5))
>>> q.put((2, 2, 5))
>>> q.get()
(2, 1, 5)
>>> q.get()
(2, 2, 5)
>>> q.get()
(2, 3, 5)
>>> q.get()
(2, 5, 5)

(Please note that this is python3 code)

2 of 4
1

from the documentation for Queue.py

There actually a PriorityQueue that automatically sort the elements in queue, but usually the elements are tuple structure (priority number, data)

I wrote some sample code here, it Q._pop() the tuple with smallest priority number:

import Queue

q = Queue.PriorityQueue()

print type(q)
print(q.queue)
q._put((4,'f'))
q._put((1,'c'))
q._put((5, 'a'))
q._put((10, 'b'))
q._put((6, 'd'))
print(q.queue)
q._get()
print(q.queue)
q._put((2,'f'))
print(q.queue)

The output is:

<type 'instance'>
[]
[(1, 'c'), (4, 'f'), (5, 'a'), (10, 'b'), (6, 'd')]
[(4, 'f'), (6, 'd'), (5, 'a'), (10, 'b')]
[(2, 'f'), (4, 'f'), (5, 'a'), (10, 'b'), (6, 'd')]

One thing I notice is that for the first time we print the q.queue, before we do any _get(), it doesn't show ordered queue, but once we call _get(), it always gives ordered queue.

🌐
DaniWeb
daniweb.com › programming › software-development › threads › 298434 › python-priority-queue
python priority queue [SOLVED] | DaniWeb
July 22, 2010 - I have not used any of the 3.0+ versions of python so I don't know if OrderedDict is included in those builds too, but below is a solution to get the dicts in order with OrderedDict. from Queue import PriorityQueue from collections import OrderedDict #making the priority queue object pq = PriorityQueue() #making the different dictionaries firstDict = OrderedDict([('boy','short'), ('girl','tall')]) secondDict = OrderedDict([('man','tall'), ('woman','short')]) #putting the objects in the priorityQueue with a priority number pq.put(firstDict, 1) pq.put(secondDict,2) #printing the dictionary according to their priority #lower number means higher priority while not pq.empty(): print pq.get()
🌐
Real Python
realpython.com › lessons › choosing-priority-queue
Choosing a Priority Queue (Video) – Real Python
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas. ... A priority queue is a special instance of a queue where the storage order is based on the priority of the items inside.
Published   May 11, 2021