🌐
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 › python › heap-and-priority-queue-using-heapq-module-in-python
Heap and Priority Queue using heapq module in Python - GeeksforGeeks
July 23, 2025 - The priority queue is implemented in Python as a list of tuples where the tuple contains the priority as the first element and the value as the next element. ... Consider a simple priority queue implementation for scheduling the presentations ...
Discussions

Heap/Priority Queue that supports removing arbitrary items and frequency tracking
Haven’t looked at code yet… but quick question - is it thread-safe? More on reddit.com
🌐 r/Python
6
3
October 23, 2025
A generic priority queue for Python - Stack Overflow
Update: Re comparison in heapq, I can either use a (priority, object) as Charlie Martin suggests, or just implement __cmp__ for my object. ... The fact that heapq is implemented in Python does not necessarily means that it is not fast. Why not just use it? Only try alternatives if it does not satisfy your performance needs. ... You can use 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
Peek method in Priority Queue?
The heapq object is a list. So you can peek with standard indexing. I don't think there's a way to peek on a queue.Queue, just due to how they are implemented. More on reddit.com
🌐 r/learnpython
2
1
September 26, 2020
🌐
The Python Coding Stack
thepythoncodingstack.com › p › python-heapq-heap-priority-queue
If You Love Queuing, Will You Also Love Priority Queuing? • [Club]
December 15, 2025 - It’s a tuple with two elements. The integer 2 refers to the Silver tier, which has the second priority level. Gold members get a 1 and Bronze members—you guessed it—a 3. But don’t use .append() to add Jim to service_queue. Instead, let’s use heapq.heappush() to push an item onto the heap:
🌐
Real Python
realpython.com › python-heapq-module
The Python heapq Module: Using Heaps and Priority Queues – Real Python
July 18, 2022 - Get the Source Code: Click here to get the source code you’ll use to learn about the Python heapq module in this tutorial. Heaps are concrete data structures, whereas priority queues are abstract data structures.
🌐
Medium
medium.com › @balakrishnamaduru › heap-and-priority-queue-in-python-mastering-heapq-and-queue-priorityqueue-bdab14488b43
Heap and Priority Queue in Python: Mastering heapq and queue.PriorityQueue | by Balakrishna Maduru | Medium
November 23, 2024 - Efficient task scheduling, finding ... provides heaps and priority queues through two powerful modules: heapq for lightweight, efficient heaps, and queue.PriorityQueue for thread-safe operations....
🌐
W3Schools
w3schools.com › python › ref_module_heapq.asp
Python heapq Module
Python Examples Python Compiler ....heappop(h) for _ in range(3)]) Try it Yourself » · The heapq module provides heap (priority queue) algorithms on regular Python lists....
🌐
GeeksforGeeks
geeksforgeeks.org › python › heap-queue-or-heapq-in-python
Heap queue or heapq in Python - GeeksforGeeks
A heap queue (also called a priority queue) is a data structure that allows quick access to the smallest (min-heap) or largest (max-heap) element. By default, heaps are implemented as min-heaps.
Published   2 weeks ago
🌐
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 ...
Find elsewhere
🌐
Reddit
reddit.com › r/python › heap/priority queue that supports removing arbitrary items and frequency tracking
r/Python on Reddit: Heap/Priority Queue that supports removing arbitrary items and frequency tracking
October 23, 2025 -

I created a Python heap implementation that supports:

  • Removing any item (not just the root via pop)

  • Tracking the frequency of items so that duplicates are handled efficiently

Source: https://github.com/Ite-O/python-indexed-heap
PyPI: https://pypi.org/project/indexedheap/

What My Project Does

indexedheap is a Python package that provides standard heap operations, insert (push), pop, and peek, along with additional features:

  • Remove any arbitrary item efficiently.

  • Track frequencies of items to handle duplicates.

  • Insert or remove multiple occurrences in a single operation.

  • Iterate over heap contents in sorted order without modifying the heap.

It is designed for scenarios requiring dynamic priority queues, where an item’s priority may change over time Common in task schedulers, caching systems or pathfinding algorithms.

Target Audience

  • Developers needing dynamic priority queues where priorities can increase or decrease.

  • Users who want duplicate-aware heaps for frequency tracking.

  • Engineers implementing task schedulers, caches, simulations or pathfinding algorithms in Python.

Comparison

Python’s built-in heapq vs indexedheap

Operation Description heapq indexedheap
heappush(heap, item) / insert(value) Add an item/value to the heap O(log N) O(log N) / (O(1) if item already exists and count is incremented)
heappop(heap) / pop() Remove and return the root item/value O(log N) O(log N)
heap[0] / peek() Return root item/value without removing it ✅ Manual (heap[0]) O(1)
remove(value) Remove any arbitrary value ❌ Not supported O(log(N)) for last occurence in heap, O(1) if only decrementing frequency
heappushpop(heap, item) Push then pop in a single operation O(log N) ❌ Not directly supported (use insert() + pop())
heapreplace(heap, item) Pop then push in a single operation O(log N) ❌ Not directly supported (use pop() + insert())
count(value) Get frequency of a specific value ❌ Not supported O(1)
item in heap / value in heap Membership check ⚠️ O(N) (linear scan) O(1)
len(heap) Number of elements O(1) O(1)
to_sorted_list() Return sorted elements without modifying heap ✅ Requires creating a sorted copy of the heap O(N log N) O(N log N)
iter(heap) Iterate in sorted order ✅ Requires creating a sorted copy of the heap and iterating over the copy O(N log N)) O(N log N)
heapify(list) / MinHeap(list), MaxHeap(list) Convert list to valid heap O(N) O(N)
heap1 == heap2 Structural equality check O(N) O(N)
Frequency tracking Track frequency of items rather than store duplicates ❌ Not supported ✅ Yes
Multi-inserts/removals Insert/ remove multiples of an item in a single operation ❌ Not supported ✅ Yes (see insert/ remove rows for time complexity)

Installation

pip install indexedheap

Feedback

If there is demand, I am considering adding support for heappushpop and heapreplace operations, similar to those in Python's heapq module.

Open to any feedback!

Updates

  • Updated terminology in the comparison table to show both "value" and "item" in some rows. Since the terminology used in my package for the inserted object is "value", whereas the terminology used in heapq is "item".

🌐
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. In Python, priority queues can be implemented using ...
🌐
Medium
medium.com › @2019077_13406 › priority-queue-v-s-heapq-python-a4858c0191ac
Priority Queue V/s Heapq Python. Lately, I have been solving LeetCode… | by kartik chuphal | Medium
December 15, 2024 - While implementing a solution with a priority queue, I came across two different implementation options in Python. Let’s dive into what each of them offers. Let’s just test which is faster. import time from queue import PriorityQueue, Empty import heapq def p_queue(): prior_queue = PriorityQueue() jobs = [(x, f"This is item: {x}") for x in range(1, 10 ** 5 + 1)] for job in jobs: prior_queue.put(job) while 1: try: popped_item = prior_queue.get_nowait() except Empty: break def heap_queue(): jobs = [(x, f"This is item: {x}") \ for x in range(1, 10 ** 5 + 1)] heapq.heapify(jobs) for _ in range
🌐
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 - In this article, you'll explore several implementation techniques and practical tips for Python. We'll also cover real-world applications and provide solutions for common bugs, so you can confidently use priority queues in your projects. import heapq pq = [] heapq.heappush(pq, (2, "Medium priority task")) heapq.heappush(pq, (1, "High priority task")) heapq.heappush(pq, (3, "Low priority task")) while pq: priority, task = heapq.heappop(pq) print(f"Processing {task} with priority {priority}")--OUTPUT--Processing High priority task with priority 1 Processing Medium priority task with priority 2 Processing Low priority task with priority 3
🌐
GeeksforGeeks
geeksforgeeks.org › python › difference-between-heapq-and-priorityqueue-in-python
Difference Between heapq and PriorityQueue in Python - GeeksforGeeks
July 23, 2025 - In this article, we are going to see the difference between heapq and PriorityQueue in Python. Python queue PriorityQueue is thread-safe, but heapq doesn't guarantee thread safety.
🌐
Real Python
realpython.com › ref › stdlib › heapq
heapq | Python Standard Library – Real Python
The Python heapq module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm.
🌐
Psu
courses.ems.psu.edu › geog489 › node › 2353
4.2.3 Priority Queues and Heapq | GEOG 489: Advanced Python Programming for GIS
In the following code, we again ... the highest value element. The code starts with an empty list in variable pQueue and then simulates the arrival of 100 assignments with random priority using heappush(…) to add a new assignment to the queue....
🌐
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.
🌐
Python
docs.python.org › fr › 3.13 › library › heapq.html
heapq --- Heap queue algorithm — Documentation Python 3.13.11
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')
🌐
Python
docs.python.org › fr › 3.5 › library › heapq.html
8.5. heapq — File de priorité basée sur un tas — Documentation Python 3.5.10
December 18, 2020 - 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')
🌐
Developer-service
developer-service.blog › understanding-pythons-heapq-module
Understanding Python's heapq Module
September 19, 2024 - The heapq module in Python provides an implementation of the heap queue algorithm, also known as the priority queue algorithm.