🌐
GeeksforGeeks
geeksforgeeks.org › python › priority-queue-in-python
Priority Queue in Python - GeeksforGeeks
April 26, 2025 - DSA Python · Data Science · NumPy · Pandas · Practice · Django · Flask · Last Updated : 26 Apr, 2025 · A priority queue is like a regular queue, but each item has a 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 ...
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-implement-priority-queue-in-python
How to Implement Priority Queue in Python?
1 month ago - PriorityQueue uses the sort order of the contents of the queue to decide which item to retrieve.
🌐
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 - Unlike regular queues where elements are processed in the order they arrive (FIFO), in a priority queue, elements are processed based on their priority. The highest-priority element is always retrieved first.
🌐
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
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.
🌐
redshiftzero
redshiftzero.com › post › priority-queue
Handling equal priority jobs using queue.PriorityQueue | redshiftzero
January 13, 2020 - A priority queue retrieves item based on priority, higher priority items come first. Well, what happens if you submit items that have equal priorities? It depends on how the priority queue was implemented. Read on for how this is handled in the Python standard library's queue.PriorityQueue.
Find elsewhere
🌐
Pierian Training
pieriantraining.com › home › python tutorial: creating a priority queue in python
Python Tutorial: Creating a Priority Queue in Python - Pierian Training
April 10, 2023 - These are just a few examples of how priority queues can be used in real-world applications. By using Python’s built-in `heapq` module or third-party libraries like `queue.PriorityQueue`, we can easily implement a priority queue and use it to manage data based on priority.
🌐
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. The heap algorithm automatically uses the first element of the tuple for sorting, meaning a lower number signifies a higher priority.
🌐
Stackify
stackify.com › a-guide-to-python-priority-queue
A Guide to Python Priority Queue - Stackify
February 18, 2025 - The queue.PriorityQueue class in Python’s standard library is a straightforward way to implement a priority queue. It’s built on top of a heap and offers thread-safe operations, making it suitable for multithreaded programs.
🌐
CodeSignal
codesignal.com › learn › courses › interview-prep-the-last-mile-in-python › lessons › heap-and-priority-queue-in-python
Heap and Priority Queue in Python
For example, if you want to find the n-th largest number in a list, using sorting can be costly. By leveraging Python's heapq.nlargest function, the heap data structure lets us do this efficiently. ... Priority queues are an abstraction over heaps that store elements according to their priorities.
🌐
Wander In Dev
wanderin.dev › python-interview › a-priority-queue-implementation-in-python
A Priority Queue Implementation in Python – Wander In Dev
October 6, 2024 - Our priority queue returns the task with the highest priority first. In cases where several tasks have the same priority, they are returned in the order of insertion. In the next article, we’ll explore linked lists. See you there! ... I am a full-stack developer from Panama. I enjoy programming in Python and JavaScript.
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
🌐
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.
🌐
GitHub
github.com › ajscheff › python_pq
GitHub - ajscheff/python_pq: A python priority queue
Our priority queue uses instances of the Item class to store values alongside priorities. Right now, we use a separate comparison function standard_priority_func to compare Item priorities during insertion. A cool feature of classes in most languages is operator overriding. This allows us to compare instances of a class directly using operators like <, ==, and others. Python makes it really easy to do this.
Starred by 4 users
Forked by 4 users
Languages   Python 100.0% | Python 100.0%
🌐
DigitalOcean
digitalocean.com › community › tutorials › priority-queue-python
How to Use a Priority Queue in Python | DigitalOcean
July 11, 2025 - A priority queue stores (priority, item) pairs so the element with the highest priority (or lowest, for min-heap) is removed first. Python ships two ready-made solutions: heapq and queue.PriorityQueue.
🌐
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:
🌐
iO Flood
ioflood.com › blog › python-priority-queue-practical-guide-with-examples
Python Priority Queue Module | Best Practices and Usage
July 8, 2024 - In a typical Queue, the first element to enter is the first to leave (FIFO – First In First Out). However, in a Priority Queue, this order is determined by the priority of the elements. So, an element that enters the queue later could leave earlier if its priority is higher. Python offers a built-in PriorityQueue class in the queue module.