🌐
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-queue-or-heapq-in-python
Heap queue or heapq in Python - GeeksforGeeks
Note: The heapq module allows in-place heap operations on lists, making it an efficient and simple way to implement priority queues and similar structures.
Published   April 6, 2026
Discussions

data structures - What is Python's heapq module? - Stack Overflow
I tried "heapq" and arrived at the conclusion that my expectations differ from what I see on the screen. I need somebody to explain how it works and where it can be useful. From the book Python Mo... More on stackoverflow.com
🌐 stackoverflow.com
Can you use Python's heapq methods during interviews? For instance, heapq.nlargest()
When I first started, I only use heapify, heappop and heappush. I started to use heappushpop and replace recently. I don't use nlargest and nsmallest, since there are questions specifically on these two topics. Better to learn how to do it without buildin methods first. Personally, I don't use build-in methods if that's the entire point of the question. For example, if the question is "sort this list", I wouldn't use list.sort or sorted. I will implement mergesort. If the question requires sort along the way, I would use list.sort / sorted. So similarly, if the question is "find k largest / smallest", I wouldn't use nlargest / nsmallest. I will implement the two heap method (this covers a few questions on heap). But if for some reason I need the nlargest / nsmallest for another part of the question and I happen to have a heap, I would use built-in. Personally, I think heapify is important. It's O(n) vs O(nlogn) if you heappush everything. It shows that you didn't read the docs on heapq, which has fewer than 10 methods. Not a dealbreaker, but could be a tie breaker. More on reddit.com
🌐 r/leetcode
19
43
January 12, 2025
Why there isn't a Max heap like Min heap in python?
It does, just undocumented. https://github.com/python/cpython/blob/3.12/Lib/heapq.py#L181 import heapq values = ["a", "b", "c", "d"] heapq._heapify_max(values) while values: print(heapq._heappop_max(values)) More on reddit.com
🌐 r/learnpython
10
3
July 20, 2024
Go's heap library has Remove(h, i) and Fix(h, i). Why doesn't Python's heapq library have this?
I think there's no deep reason. You can access the operation you want by going v, heap[i] = heap[i], heap.pop(); heapq._siftup(heap, i) The _siftup operation is not part of the interface but internally it needs this kind of operation to implement the others. This should give you O(log n) performance. The choice of what operations to expose in the API is a design question, and, in my opinion, the heapq library is not the best designed. (edit: Note that here the index is the index in the heap, the heap is not a sorted structure [i dont know about Go] so it's probably not so useful an operation in Python!) More on reddit.com
🌐 r/Python
13
2
June 4, 2022
🌐
W3Schools
w3schools.com › python › ref_module_heapq.asp
Python heapq Module
Python Overview Python Built-in ... Study Plan Python Interview Q&A Python Bootcamp Python Training ... import heapq h = [] heapq.heappush(h, 3) heapq.heappush(h, 1) heapq.heappush(h, 2) print([heapq.heappop(h) for _ in ...
🌐
Medium
cleverzone.medium.com › exploring-pythons-heapq-module-b0c9d131545c
Exploring Python's heapq Module - Abhijeet Kumar
June 17, 2024 - Exploring Python’s heapq Module Python’s heapq module offers a solution for implementing heaps and priority queues, perfect for tasks like scheduling and managing priority lists. In this blog we …
🌐
Real Python
realpython.com › python-heapq-module
The Python heapq Module: Using Heaps and Priority Queues – Real Python
July 18, 2022 - First, you need to import the Python heapq module: ... You’ll use the functions from the Python heapq module to maintain a heap that will help you find the position with the shortest known path at each iteration.
🌐
Real Python
realpython.com › ref › stdlib › heapq
heapq | Python Standard Library – Real Python
>>> import heapq >>> tasks = [(3, "write code"), (1, "write specs"), (2, "test code")] >>> heapq.heapify(tasks) >>> while tasks: ... priority, task = heapq.heappop(tasks) ... print(f"Processing task: {task} with priority {priority}") ...
🌐
Medium
dpythoncodenemesis.medium.com › understanding-pythons-heapq-module-a-guide-to-heap-queues-cfded4e7dfca
Understanding Python’s Heapq Module: A Guide to Heap Queues | by Python Code Nemesis | Medium
October 21, 2023 - Heapq is a module in Python that provides an implementation of the heap queue algorithm, also known as the priority queue algorithm.
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-heapq-heappop-method
Python heapq.heappop() Method - GeeksforGeeks
June 11, 2026 - Explanation: heapq.heappop(h) removes the minimum element from h and returns it.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-heapq-heappush-method
Python heapq.heappush() Method - GeeksforGeeks
June 11, 2026 - Explanation: Each call to heapq.heappush() inserts a value into h and rearranges the heap so that the minimum element stays at index 0.
🌐
APXML
apxml.com › courses › data-structures-algorithms-ml › chapter-5-heaps-priority-queues-ml › python-heapq
Python heapq Module for Heap Operations
If you already have a list of items and want to turn it into a valid heap, you could repeatedly call heappush. However, a more efficient method is heapq.heapify(list).
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-heapq-heapify-method
Python heapq.heapify() Method - GeeksforGeeks
June 26, 2026 - DSA Python · Data Science · NumPy · Pandas · Practice · Django · Flask · Last Updated : 26 Jun, 2026 · heapq.heapify() method converts a list into a valid min-heap. After heapification, the smallest element is placed at the beginning ...
🌐
Python
docs.python.org › 3.0 › library › heapq.html
heapq — Heap queue algorithm — Python v3.0.1 documentation
>>> from heapq import heappush, heappop >>> heap = [] >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] >>> for item in data: ... heappush(heap, item) ... >>> ordered = [] >>> while heap: ... ordered.append(heappop(heap)) ...
🌐
DEV Community
dev.to › devasservice › understanding-pythons-heapq-module-1n37
Understanding Python's heapq Module - DEV Community
September 19, 2024 - The heapq module provides functions to perform heap operations on a regular Python list.
Top answer
1 of 4
118

The heapq module maintains the heap invariant, which is not the same thing as maintaining the actual list object in sorted order.

Quoting from the heapq documentation:

Heaps are binary trees for which every parent node has a value less than or equal to any of its children. This implementation uses arrays for which heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2] for all k, counting elements from zero. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that its smallest element is always the root, heap[0].

This means that it is very efficient to find the smallest element (just take heap[0]), which is great for a priority queue. After that, the next 2 values will be larger (or equal) than the 1st, and the next 4 after that are going to be larger than their 'parent' node, then the next 8 are larger, etc.

You can read more about the theory behind the datastructure in the Theory section of the documentation. You can also watch this lecture from the MIT OpenCourseWare Introduction to Algorithms course, which explains the algorithm in general terms.

A heap can be turned back into a sorted list very efficiently:

def heapsort(heap):
    return [heapq.heappop(heap) for _ in range(len(heap))]

by just popping the next element from the heap. Using sorted(heap) should be faster still, however, as the TimSort algorithm used by Python’s sort will take advantage of the partial ordering already present in a heap.

You'd use a heap if you are only interested in the smallest value, or the first n smallest values, especially if you are interested in those values on an ongoing basis; adding new items and removing the smallest is very efficient indeed, more so than resorting the list each time you added a value.

2 of 4
41

Your book is wrong! As you demonstrate, a heap is not a sorted list (though a sorted list is a heap). What is a heap? To quote Skiena's Algorithm Design Manual

Heaps are a simple and elegant data structure for efficiently supporting the priority queue operations insert and extract-min. They work by maintaining a partial order on the set of elements which is weaker than the sorted order (so it can be efficient to maintain) yet stronger than random order (so the minimum element can be quickly identified).

Compared to a sorted list, a heap obeys a weaker condition the heap invariant. Before defining it, first think why relaxing the condition might be useful. The answer is the weaker condition is easier to maintain. You can do less with a heap, but you can do it faster.

A heap has three operations:

  1. Find-Minimum is O(1)
  2. Insert O(log n)
  3. Remove-Min O(log n)

Crucially Insert is O(log n) which beats O(n) for a sorted list.

What is the heap invariant? "A binary tree where parents dominate their children". That is, "p ≤ c for all children c of p". Skiena illustrates with pictures and goes on to demonstrate the algorithm for inserting elements while maintaining the invariant. If you think a while, you can invent them yourself. (Hint: they are known as bubble up and bubble down)

The good news is that batteries-included Python implements everything for you, in the heapq module. It doesn't define a heap type (which I think would be easier to use), but provides them as helper functions on list.

Moral: If you write an algorithm using a sorted list but only ever inspect and remove from one end, then you can make the algorithm more efficient by using a heap.

For a problem in which a heap data structure is useful, read https://projecteuler.net/problem=500

🌐
FavTutor
favtutor.com › blogs › heapq-python
Python's heapq module: Implementing heap queue algorithm
May 4, 2023 - The Python heapq module is part of its Standard Library and is used to implement the heap queue algorithm, also referred to as the priority queue algorithm. This offers functions for building and modifying heap data structures.
🌐
TechBeamers
techbeamers.com › python-heapq
The heapq (Heap Queue) Module in Python - TechBeamers
November 30, 2025 - Heaps are the most efficient data structure when it comes to accessing the smallest or largest element in constant time (O(1)). Python provides the heapq module (heap queue or priority queue) which simulates min heap using lists.
🌐
Python Cheat Sheet
pythonsheets.com › notes › basic › python-heap.html
Heap — Python Cheat Sheet
>>> import heapq >>> pq = [] >>> heapq.heappush(pq, (2, "medium")) >>> heapq.heappush(pq, (1, "high")) >>> heapq.heappush(pq, (3, "low")) >>> [heapq.heappop(pq) for _ in range(len(pq))] [(1, 'high'), (2, 'medium'), (3, 'low')] For custom objects, implement the __lt__ method to define comparison behavior:
🌐
iO Flood
ioflood.com › blog › using-python-heapq-module-for-heaps-and-priority-queues
Using Python Heapq Module for Heaps and Priority Queues
February 5, 2024 - Python’s heapq module is a powerful tool that implements the heap queue algorithm (priority queue algorithm) using the binary heap data structure. It provides functions to create a heap, add/remove elements, and perform heap operations efficiently.
🌐
GeeksforGeeks
geeksforgeeks.org › heap-and-priority-queue-using-heapq-module-in-python
Heap and Priority Queue using heapq module in Python - GeeksforGeeks
January 10, 2023 - 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 of students based on their roll number. Here roll number decides the priority of the student to present. Since it is a min-heap, roll number 1 is considered to be of the highest priority. ... # import modules import heapq as hq # list of students list_stu = [(5,'Rina'),(1,'Anish'),(3,'Moana'),(2,'cathy'),(4,'Lucy')] # Arrange based on the roll number hq.heapify(list_stu) print("The order of presentation is :") for i in list_stu: print(i[0],':',i[1])
🌐
CodeSignal
codesignal.com › learn › courses › understanding-and-using-trees-in-python › lessons › unraveling-heaps-theory-operations-and-implementations-in-python
Theory, Operations, and Implementations in Python
Python offers a vast range of libraries, including a built-in module, heapq, which allows for the creation and manipulation of heaps with ease. import heapq heap = [] # Insert in heap heapq.heappush(heap, 4) heapq.heappush(heap, 9) heapq.heappush(heap, 6) print("Heap after insertion: ", heap) ...