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
๐ŸŒ
Built In
builtin.com โ€บ data-science โ€บ priority-queues-in-python
Introduction to Priority Queues in Python | Built In
Summary: A priority queue in Python allows elements to be processed based on assigned priority rather than arrival order. It can be implemented using lists, the heapq module for efficiency, or the thread-safe PriorityQueue class for concurrent ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ priority-queue-in-python
Priority Queue in Python - GeeksforGeeks
April 26, 2025 - Huffman Encoding (Data Compression) combines least frequent symbols using a priority queue to reduce data size. Merging Multiple Sorted Lists merges sorted lists by selecting the smallest element from each list. A Search Algorithm (Pathfinding) prioritizes nodes based on cost to find the shortest path in navigation or games.
Discussions

A generic priority queue for Python - Stack Overflow
I need to use a priority queue in my Python code, and: am looking for any fast implementations for priority queues optimally, I'd like the queue to be generic (i.e. work well for any object with a More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to implement Priority Queues in Python? - Stack Overflow
I undestand priority queue theoretically pretty well and thus the possible DS. But the question is about its implementation in Python which has very different set of DS. More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to put items into priority queues? - Stack Overflow
The lowest valued entries are retrieved first (the lowest valued entry is the one returned by sorted(list(entries))[0]). A typical pattern for entries is a tuple in the form: (priority_number, data). It appears the queue will be sorted by priority then data, which may not be always correct. More on stackoverflow.com
๐ŸŒ stackoverflow.com
Is the queue in an implementation of a LRU cache a priority queue?
It's not necessary to have a priority queue, you can do it with a regular queue (and thus in expected constant time per operation), but the queue has to be implemented as a bidirectional linked list - i.e., each node of the queue stores pointers to both the previous and the next node in the queue. At any moment, the queue will contain the elements in your LRU cache in the order in which they were most recently used. The trick is how to maintain the order. The answer is that in your main hashmap you will store, for each key, not just the cached value but also a pointer into the queue. Whenever you access an element that's already in your cache, you can use that pointer to find it and remove it from the queue. Then, you reinsert it at the "most recent" end of the queue and you update the pointer to it. More on reddit.com
๐ŸŒ r/algorithms
10
1
October 5, 2022
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ priority-queue-python
How to Use a Priority Queue in Python | DigitalOcean
July 11, 2025 - A priority queue in Python is a data structure that allows elements to be added and removed based on their priority. It is a type of queue where each element is associated with a priority, and elements are removed in order of their priority.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ heapq.html
heapq โ€” Heap queue algorithm
Source code: Lib/heapq.py This module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm. Min-heaps are binary trees for which every parent node has ...
๐ŸŒ
Stackify
stackify.com โ€บ a-guide-to-python-priority-queue
A Guide to Python Priority Queue - Stackify
February 18, 2025 - The queue.PriorityQueue class is part of Pythonโ€™s queue module and offers a simple way to create thread-safe priority queues. Key Features: Thread safe, making it ideal for multithreaded applications.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ queue.html
queue โ€” A synchronized queue class
February 23, 2026 - 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.
Find elsewhere
๐ŸŒ
Linode
linode.com โ€บ docs โ€บ guides โ€บ python-priority-queue
What is the Python Priority Queue? | Linode Docs
June 17, 2022 - However, it is often necessary to account for the priority of each item when determining processing order. A queue that retrieves and removes items based on their priority as well as their arrival time is called a priority queue.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ what-is-the-python-priority-queue
What is the Python priority queue?
Instead of dequeuing the oldest element, a priority queue sorts and dequeues elements based on their priorities. Priority queues are used to handle scheduling problems where some tasks are prioritized over others.
๐ŸŒ
Real Python
realpython.com โ€บ queue-in-python
Python Stacks, Queues, and Priority Queues in Practice โ€“ Real Python
December 1, 2023 - Python has the heapq module, which conveniently provides a few functions that can turn a regular list into a heap and manipulate it efficiently. The two functions thatโ€™ll help you build a priority queue are:
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

Copy   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.

๐ŸŒ
Blogboard
blogboard.io โ€บ blog โ€บ knowledge โ€บ priority-queue-in-python
Priority Queue in Python
April 9, 2024 - a priority queue is an abstract data type similar to a regular queue or stack data structure in which each element additionally has a priority associated with it. In a priority queue, an element with high priority is served before an element ...
๐ŸŒ
Hostman
hostman.com โ€บ tutorials โ€บ implementing a priority queue in python
Implementing a Priority Queue in Python: A Comprehensive Guide
December 29, 2025 - A priority queue is a special type of queue where each element is associated with a priority. In a priority queue, elements are dequeued in order of their priority, rather than their insertion order.
Price ย  $
Call ย  +1 844 286 2130
Address ย  1999 Harrison St 1800 9079, 94612, Oakland
๐ŸŒ
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. If two elements have the same priority, they are served according to their order in the queue.
๐ŸŒ
iO Flood
ioflood.com โ€บ blog โ€บ python-priority-queue-practical-guide-with-examples
Python Priority Queue Examples | Best Practices and Usage
July 8, 2024 - A priority queue can be implemented using the Python heapq module. The priority queue is instantiated with priority_queue = []. Elements can be added with syntax such as, heapq.heappush(priority_queue, (2, 'task 2')). In a Python priority queue, ...
๐ŸŒ
Python Guides
pythonguides.com โ€บ priority-queue-in-python
Priority Queue in Python
December 12, 2025 - In many real-world applications ... priorities can change. Optimize performance with O(log n) insertion and removal. The heapq module is the go-to solution in Python for priority queues....
๐ŸŒ
Replit
replit.com โ€บ home โ€บ discover โ€บ how to implement a priority queue in python
How to implement a priority queue in Python | Replit
March 3, 2026 - Python's heapq module provides an efficient min-heap implementation, which is perfect for a priority queue. It operates directly on a list, using tuples like (priority, task) to organize data.
๐ŸŒ
Programiz
programiz.com โ€บ dsa โ€บ priority-queue
Priority Queue Data Structure
Become a certified Python programmer. Try Programiz PRO! ... A priority queue is a special type of queue in which each element is associated with a priority value. And, elements are served on the basis of their priority.
Top answer
1 of 3
37

Just use the second item of the tuple as a secondary priority if a alphanumeric sort on your string data isn't appropriate. A date/time priority would give you a priority queue that falls back to a FIFIO queue when you have multiple items with the same priority. Here's some example code with just a secondary numeric priority. Using a datetime value in the second position is a pretty trivial change, but feel free to poke me in comments if you're not able to get it working.

Code

import Queue as queue

prio_queue = queue.PriorityQueue()
prio_queue.put((2, 8, 'super blah'))
prio_queue.put((1, 4, 'Some thing'))
prio_queue.put((1, 3, 'This thing would come after Some Thing if we sorted by this text entry'))
prio_queue.put((5, 1, 'blah'))

while not prio_queue.empty():
    item = prio_queue.get()
    print('%s.%s - %s' % item)

Output

1.3 - This thing would come after Some Thing if we didn't add a secondary priority
1.4 - Some thing
2.8 - super blah
5.1 - blah

Edit

Here's what it looks like if you use a timestamp to fake FIFO as a secondary priority using a date. I say fake because it's only approximately FIFO as entries that are added very close in time to one another may not come out exactly FIFO. I added a short sleep so this simple example works out in a reasonable way. Hopefully this helps as another example of how you might get the ordering you're after.

import Queue as queue
import time

prio_queue = queue.PriorityQueue()
prio_queue.put((2, time.time(), 'super blah'))
time.sleep(0.1)
prio_queue.put((1, time.time(), 'This thing would come after Some Thing if we sorted by this text entry'))
time.sleep(0.1)
prio_queue.put((1, time.time(), 'Some thing'))
time.sleep(0.1)
prio_queue.put((5, time.time(), 'blah'))

while not prio_queue.empty():
    item = prio_queue.get()
    print('%s.%s - %s' % item)
2 of 3
32

As far as I know, what you're looking for isn't available out of the box. Anyway, note that it wouldn't be hard to implement:

from Queue import PriorityQueue

class MyPriorityQueue(PriorityQueue):
    def __init__(self):
        PriorityQueue.__init__(self)
        self.counter = 0

    def put(self, item, priority):
        PriorityQueue.put(self, (priority, self.counter, item))
        self.counter += 1

    def get(self, *args, **kwargs):
        _, _, item = PriorityQueue.get(self, *args, **kwargs)
        return item


queue = MyPriorityQueue()
queue.put('item2', 1)
queue.put('item1', 1)

print queue.get()
print queue.get()

Example output:

item2
item1
๐ŸŒ
dbader.org
dbader.org โ€บ blog โ€บ priority-queues-in-python
Priority Queues in Python โ€“ dbader.org
April 12, 2017 - A priority queue is a container data structure that manages a set of records with totally-ordered keys (for example, a numeric weight value) to provide quick access to the record with the smallest or largest key in the set.