heapq heaps are nothing more than lists whose elements respect a special (non-unique) order.

You can use len(heap) on it just like you would on any other list.

In [1]: import heapq
In [2]: heap = [40, 10, 20, 30]
In [3]: heapq.heapify(heap)
In [4]: heap
Out[4]: [10, 30, 20, 40]

In [5]: heapq.heappop(heap)
Out[5]: 10

In [6]: heap
Out[6]: [20, 30, 40]

In [7]: len(heap)
Out[7]: 3

You should also read the python documentation for heapq: the example section should interest you.

Answer from loxaxs on Stack Overflow
🌐
Python
docs.python.org › 3 › library › heapq.html
heapq — Heap queue algorithm
>>> def heapsort(iterable): ... h = [] ... for value in iterable: ... heappush(h, value) ... return [heappop(h) for i in range(len(h))] ...
🌐
Johnlekberg
johnlekberg.com › blog › 2020-11-01-stdlib-heapq.html
Python's heapq module
heapq.heapreplace has the same effect as calling heapq.heappop then heapq.heappush. But, heapreplace is more efficient than calling heappop and heappush individually. And heapreplace does not change the size of the heap. ... Keep track of the heap size using len.
🌐
Real Python
realpython.com › python-heapq-module
The Python heapq Module: Using Heaps and Priority Queues – Real Python
July 18, 2022 - The heap of candidates is organized by the length of the shortest known path and is managed with the help of the functions in the Python heapq module.
🌐
Gitbook
sisyphus.gitbook.io › project › python-notes › python-priority-queue-heapq
Python priority queue -- heapq - The Truth of Sisyphus - GitBook
These two make it possible to view the heap as a regular Python list without surprises: heap[0] is the smallest item, and heap.sort() maintains the heap invariant! To create a heap, use a list initialized to [], or you can transform a populated list into a heap via function heapify(). ... class KthLargest(object): def __init__(self, k, nums): self.window = nums self.k = k heapq.heapify(self.window) # Transform list x into a heap, in-place, in linear time. while len(self.window) > k: heapq.heappop(self.window) # Pop and return the smallest item from the heap, maintaining the heap invariant.
🌐
GeeksforGeeks
geeksforgeeks.org › python › heap-queue-or-heapq-in-python
Heap queue or heapq in Python - GeeksforGeeks
Python provides a built-in module called heapq that allows to create and work with heap queues
Published   3 weeks ago
🌐
Python
docs.python.org › 3.8 › library › heapq.html
heapq — Heap queue algorithm — Python 3.8.20 documentation
>>> def heapsort(iterable): ... h = [] ... for value in iterable: ... heappush(h, value) ... return [heappop(h) for i in range(len(h))] ...
🌐
APXML
apxml.com › courses › data-structures-algorithms-ml › chapter-5-heaps-priority-queues-ml › python-heapq
Python heapq Module for Heap Operations
# Example using heappushpop (maintaining top 3 elements) top_k_heap = [10, 20, 30] # Assume this is already a heap heapq.heapify(top_k_heap) # Ensure it's a heap # Process new items, keeping only the top 3 largest (using min-heap for smallest) # If we model this as keeping the 'k' largest using a min-heap of size 'k', # we push a new item and pop the smallest if the heap size exceeds 'k'. # heappushpop is useful if the heap is already at size 'k'. new_item = 5 if len(top_k_heap) < 3: heapq.heappush(top_k_heap, new_item) elif new_item > top_k_heap[0]: # Only proceed if larger than the smallest
Find elsewhere
🌐
Python
docs.python.org › 3.9 › library › heapq.html
heapq — Heap queue algorithm — Python 3.9.24 documentation
>>> def heapsort(iterable): ... h = [] ... for value in iterable: ... heappush(h, value) ... return [heappop(h) for i in range(len(h))] ...
🌐
GitHub
github.com › python › cpython › blob › main › Lib › heapq.py
cpython/Lib/heapq.py at main · python/cpython
The Python programming language. Contribute to python/cpython development by creating an account on GitHub.
Author   python
🌐
AlgoTree
algotree.org › algorithms › heap data structure
Python : Max Heap / Min Heap Using HeapQ :: AlgoTree
# We override the __lt__ (less than) or __gt__ (greater than) # function to convert the heapq of the objects into a min-heap or a max-heap # Create a max-heap by overriding the __gt__ operator. # def __gt__ (self, arg_obj) : # return self.freq < arg_obj.freq # Get a max-heap by overriding the __lt__ operator. def __lt__ (self, arg_obj) : return self.height > arg_obj.height def __eq__ (self, arg_obj) : return self.height == arg_obj.height class River : def __init__ (self, name, length) : self.name = name self.length = length # Create a min-heap by overriding the __lt__ operator.
🌐
Real Python
realpython.com › ref › stdlib › heapq
heapq | Python Standard Library – Real Python
In this example, you use the heapq module to manage tasks by their priority, ensuring that tasks are processed in the correct order. ... In this step-by-step tutorial, you'll explore the heap and priority queue data structures. You'll learn what kinds of problems heaps and priority queues are useful for and how you can use the Python heapq module to solve them.
🌐
Python Cheat Sheet
pythonsheets.com › notes › basic › python-heap.html
Heap — Python Cheat Sheet
>>> import heapq >>> # Max heap using negation >>> h = [] >>> for x in [5, 1, 3, 2, 6]: ... heapq.heappush(h, -x) ... >>> [-heapq.heappop(h) for _ in range(len(h))] [6, 5, 3, 2, 1] For custom objects, implement __lt__ with reversed comparison: import heapq class MaxHeapItem: def __init__(self, val): self.val = val def __lt__(self, other): return self.val > other.val # reversed for max heap h = [] for x in [5, 1, 3]: heapq.heappush(h, MaxHeapItem(x)) print(heapq.heappop(h).val) # 5 (largest)
🌐
Thecodeforge
thecodeforge.io › home › python › python heapq module explained — min-heaps, priority queues and real-world patterns
Python heapq Module Explained — Min-Heaps, Priority Queues and Real-World Patterns | TheCodeForge
March 6, 2026 - Add an assertion on heap size as a guard: assert len(heap) < MAX_HEAP_SIZE. Monitor heap length as a production metric. nlargest is slower than expected on a large dataset→Check the ratio of k to n. If k > n/2, heapq.nlargest overhead exceeds ...
🌐
GitHub
github.com › enthought › Python-2.7.3 › blob › master › Lib › heapq.py
Python-2.7.3/Lib/heapq.py at master · enthought/Python-2.7.3
from _heapq import * except ImportError: pass · · def merge(*iterables): '''Merge multiple sorted inputs into a single sorted output. · Similar to sorted(itertools.chain(*iterables)) but returns a generator, does not pull the data into memory all at once, and assumes that each of ·
Author   enthought
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

🌐
TutorialsPoint
tutorialspoint.com › python_data_structure › python_heaps.htm
Python - Heaps
import heapq H = [21,1,45,78,3,5] # Covert to a heap heapq.heapify(H) print(H) # Add element heapq.heappush(H,8) print(H)