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
I hope this article helps you get ... can be implemented in Python by using a list, importing the heapq module or importing the queue module and using the PriorityQueue class....
๐ŸŒ
Hostman
hostman.com โ€บ tutorials โ€บ implementing-a-priority-queue-in-python
Implementing a Priority Queue in Python: A Comprehensive Guide
Python provides a built-in library called heapq that can be used to implement priority queues. The heapq module offers an efficient way to maintain a heap, which is a binary tree where the parent node is always smaller than or equal to its child nodes (min-heap).
Discussions

A generic priority queue for Python - Stack Overflow
I am implementing a priority queue in python 3 using queue.PriorityQueue like this- Copyfrom queue import PriorityQueue class PqElement(object): def __init__(self, value: int): self.val = value #Custom Compare Function (less than or equsal) def __lt__(self, other): """self < obj.""" return ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
python - How to put items into priority queues? - Stack Overflow
A date/time priority would give ... 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. import Queue as queue ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Is there a better priority queue?
You don't have to give a priority queue a tuple of (priority, value), that's just the most common use case. If you wanted to base priority on 3 variables, you could give (a, b, c, value), where ties between a values are broken by the b values, etc. More on reddit.com
๐ŸŒ r/Python
5
6
November 21, 2017
How to get the largest element from the priority queue?
Put the negative value. Negate again after retrieval. More on reddit.com
๐ŸŒ r/learnpython
6
2
July 4, 2022
๐ŸŒ
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 - Let's learn how to use Priority Queue in Python with queue.PriorityQueue and heapdict. queue.PriorityQueue is a constructor to create a priority queue, where items are stored in priority order (lower priority numbers are retrieved first).
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ queue.html
queue โ€” A synchronized queue class
The lowest valued entries are retrieved ... in a class that ignores the data item and only compares the priority number: from dataclasses import ......
๐ŸŒ
Stackify
stackify.com โ€บ a-guide-to-python-priority-queue
A Guide to Python Priority Queue - Stackify
February 18, 2025 - ... from queue import PriorityQueue # Create a PriorityQueue instance pq = PriorityQueue() # Adding elements with priorities (priority, value) pq.put((2, "Task B")) pq.put((1, "Task A")) pq.put((3, "Task C")) # Removing elements while not ...
๐ŸŒ
iO Flood
ioflood.com โ€บ blog โ€บ python-priority-queue-practical-guide-with-examples
Python Priority Queue Examples | Best Practices and Usage
July 8, 2024 - 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, each element is associated and served according to a specific priority.
Find elsewhere
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 Guides
pythonguides.com โ€บ priority-queue-in-python
Priority Queue in Python
December 12, 2025 - For more control, I sometimes create a custom priority queue class encapsulating heapq operations. This makes the code cleaner and reusable. import heapq class PriorityQueue: def __init__(self): self._queue = [] self._index = 0 def push(self, item, priority): # Use index to maintain FIFO order among same priority items heapq.heappush(self._queue, (priority, self._index, item)) self._index += 1 def pop(self): return heapq.heappop(self._queue)[-1] # Example usage pq = PriorityQueue() pq.push("Pay bills", 2) pq.push("Buy groceries", 3) pq.push("Call plumber", 1) while True: try: task = pq.pop() print(f"Next task: {task}") except IndexError: break
๐ŸŒ
Linode
linode.com โ€บ docs โ€บ guides โ€บ python-priority-queue
What is the Python Priority Queue? | Linode Docs
June 17, 2022 - The example in this section ... new entries, and how to remove all remaining items from the queue. Import the PriorityQueue package from the queue module....
๐ŸŒ
Blogboard
blogboard.io โ€บ blog โ€บ knowledge โ€บ priority-queue-in-python
Priority Queue in Python
April 9, 2024 - Python comes with a built-in PriorityQueue class, contained in the queue module. In the simplest case, an entry in the priority queue will be a tuple (priority_number, data). Here's a dummy example of how to use it: import random from queue import PriorityQueue ...
๐ŸŒ
Real Python
realpython.com โ€บ queue-in-python
Python Stacks, Queues, and Priority Queues in Practice โ€“ Real Python
December 1, 2023 - Notice that the priority comes before the value to take advantage of how Python compares tuples. Unfortunately, there are a few problems with the above implementation that become apparent when you try to use it: ... >>> from queues import PriorityQueue >>> CRITICAL = 3 >>> IMPORTANT = 2 >>> NEUTRAL = 1 >>> messages = PriorityQueue() >>> messages.enqueue_with_priority(IMPORTANT, "Windshield wipers turned on") >>> messages.enqueue_with_priority(NEUTRAL, "Radio station tuned in") >>> messages.enqueue_with_priority(CRITICAL, "Brake pedal depressed") >>> messages.enqueue_with_priority(IMPORTANT, "Hazard lights turned on") >>> messages.dequeue() (1, 'Radio station tuned in')
๐ŸŒ
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 ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ priority-queue-in-python
Priority Queue in Python - GeeksforGeeks
April 26, 2025 - ... The Queue module is primarily ... object that can take a distinct number of items. The get() and put() methods are used to add or remove items from a queue respectively....
๐ŸŒ
Career Karma
careerkarma.com โ€บ blog โ€บ python โ€บ python priority queue: a guide
Python Priority Queue: A Guide | Career Karma
December 1, 2023 - The queue.PriorityQueue class creates a Python priority queue. This class is part of the Python queue library. You need to import the queue library to use this class.
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ priority-queue-python
How to Use a Priority Queue in Python | DigitalOcean
July 11, 2025 - Hereโ€™s an example of how to use queue.PriorityQueue to implement a priority queue: from queue import PriorityQueue import threading, random, time # Create a PriorityQueue instance pq = PriorityQueue() # Define a worker function that will process tasks from the priority queue def worker(): ...
๐ŸŒ
Bogotobogo
bogotobogo.com โ€บ python โ€บ python_PriorityQueue_heapq_Data_Structure.php
Python Tutorial: Data Structure - Priority Queue & heapq - 2020
try: import Queue as Q # ver. < 3.0 except ImportError: import queue as Q class Skill(object): def __init__(self, priority, description): self.priority = priority self.description = description print 'New Level:', description return def
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ program for priority queue in python
Program for Priority Queue in Python - Scaler Topics
December 13, 2022 - The below example shows how to ... of new entries, and how to delete all remaining items from the queue. The first step is to import the PriorityQueue package from the queue module....
๐ŸŒ
Shapehost
shape.host โ€บ home โ€บ resources โ€บ the python priority queue: a comprehensive guide
Understanding Python Priority Queue: A Comprehensive Guide - Shapehost
December 29, 2023 - Hereโ€™s an example that demonstrates how to use it: from queue import PriorityQueue # Create a priority queue q = PriorityQueue() # Add passengers to the queue q.put((2, "Smith")) # Business class q.put((1, "Jones")) # First class q.put((4, "Wilson")) # Standby class # Remove the highest priority ...
๐ŸŒ
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 - The heapq module provides an implementation of heap queue algorithm which is used to create a Priority Queue. Heap data structure is binary tree where each node has a parent node and at most two child nodes.