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
🌐
Python
docs.python.org β€Ί 3 β€Ί library β€Ί heapq.html
heapq β€” Heap queue algorithm
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 a value less than or equal to any of its children.
🌐
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
Creating a python priority Queue - Stack Overflow
I would like to build a priority queue in python in which the queue contains different dictionaries with their priority numbers. So when a "get function" is called, the dictionary with the highest More on stackoverflow.com
🌐 stackoverflow.com
tips on how to make a linear priority queue?
https://www.educative.io/answers/what-is-the-python-priority-queue More on reddit.com
🌐 r/learnpython
2
1
January 19, 2023
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
🌐
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 ...
🌐
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.
🌐
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 - 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. I’ll use the terms β€˜heap queue’ and β€˜priority queue’ interchangeably in this post.
Find elsewhere
🌐
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...
🌐
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.
🌐
Akamai
akamai.com β€Ί cloud β€Ί 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.
🌐
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 - # 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 empty list #======================== p_queue = [] # note that you will get an error if you do p_queue = heapq() # use heappush() heapq.heappush(p_queue, 10) heapq.heappush(p_queue, 5) heapq.heappush(p_queue, 20) print(p_queue) # Regardless of the order elements are pushed into heapq, # it always pops the smallest element.
🌐
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 β€Ί 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.
🌐
Programiz
programiz.com β€Ί dsa β€Ί priority-queue
Priority Queue Data Structure
A priority queue is a special type of queue in which each element is associated with a priority and is served according to its priority. In this tutorial, you will understand the priority queue and its implementations in Python, Java, C, and C++.
🌐
Reddit
reddit.com β€Ί r/learnpython β€Ί tips on how to make a linear priority queue?
r/learnpython on Reddit: tips on how to make a linear priority queue?
January 19, 2023 -
class PriorityQueue:
    def __init__(self, data, priority):
        self.data = data
        self.priority = priority
        self.dict = {}

    def enqueue(self):
        if self.priority is not self.dict:
            self.dict[self.data] = self.priority
            return self.dict
        elif self.priority in self.dict:
            # ?
            return self.dict

x = PriorityQueue("Potato", 2)
print(x.enqueue())

I am trying to make a priority queue from scratch kinda, but I am totally lost. I want it to be where the user is asked to input a single string e.g. Bob1 and it splits the string and adds the value/priority ... Also any tips on queues as a whole would be great as I find them kind of difficult. Thanks.

🌐
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.
🌐
Wikipedia
en.wikipedia.org β€Ί wiki β€Ί Priority_queue
Priority queue - Wikipedia
1 month ago - In computer science, a priority queue is an abstract data type similar to a regular queue where each element has an associated priority determining its order of service. Priority queue serves highest priority items first. Priority values have to be instances of an ordered data type, and higher ...
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.

🌐
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:
🌐
PREP INSTA
prepinsta.com β€Ί home β€Ί data structures and algorithms in python β€Ί introduction to priority queues using python
Introduction to Priority Queues using Python | PrepInsta
July 16, 2025 - A Priority Queue is a special type of queue in which each element is associated with a priority, and elements are served based on their priority. In Python, it can be implemented using heapq, which provides a min-heap by default.