Solution: Wrap data with the new comparison

Since the builtin functions don't directly support cmp functions, we need to build new variants of heapify and heappop:

from heapq import heapify, heappop
from functools import cmp_to_key

def new_heapify(data, cmp):
    s = list(map(cmp_to_key(cmp), data))
    heapify(s)
    return s

def new_heappop(data):
    return heappop(data).obj

Those are used just like your example:

>>> l = [ ['a', 3], ['b', 1] ]
>>> def foo(x, y):
...    return x[1]-y[1]
...
>>> heap = new_heapify(l, cmp=foo)
>>> new_heappop(heap)
['b', 1]

Solution: Store Augmented Tuples

A more traditional solution is to store (priority, task) tuples on the heap:

pq = [ ]
heappush(pq, (10, task1))
heappush(pq, (5, task2))
heappush(pq, (15, task3))
priority, task = heappop(pq)

This works fine as long as no two tasks have the same priority; otherwise, the tasks themselves are compared (which might not work at all in Python 3).

The regular docs give guidance on how to implement priority queues using heapq:

http://docs.python.org/library/heapq.html#priority-queue-implementation-notes

Answer from Raymond Hettinger on Stack Overflow
🌐
Python
docs.python.org › 3 › library › heapq.html
heapq — Heap queue algorithm
To create a heap, use a list initialized as [], or transform an existing list into a min-heap or max-heap using the heapify() or heapify_max() functions, respectively.
🌐
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 · Example: Converting a normal list into a heap using heapify().
Published   2 weeks ago
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-heapq-heapify-method
Python heapq.heapify() Method - GeeksforGeeks
July 23, 2025 - The heapq.heapify() function in Python is used to transform a regular list into a valid min-heap. A min-heap is a binary tree where the smallest element is always at the root.
🌐
Educative
educative.io › answers › what-is-the-heapqheapify-module-in-python
What is the heapq.heapify() module in Python?
The heapq module is an inbuilt module in Python that offers APIs for different operations of the heap data structure. The module provides min-heap implementation where the key of the parent is less than or equal to those of its children. Some of the functions offered by the module are heapify and heappushpop, among others.
🌐
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
The "Heapify" method is an intriguing function used to rearrange elements in heap data structures. It assists in preserving the heap property within the heap. In Python, this operation can be executed using the heapify() function.
🌐
Roman Glushko
romaglushko.com › home › blog › heapify ✌️
Heapify ✌️ - Blog by Roman Glushko
May 16, 2021 - from typing import List class PriorityQueue: """ Represents the heap and preserves the heap property during adding/removing elements """ items: List[int] def __init__(self, items: List[int]): self.items = self.build_heap(items) def build_heap(self, items: List[int]) -> List[int]: """ Turn an unsorted array into a heap """ items_count = len(items) for i in range(items_count // 2, -1, -1): items = self.heapify(items, i) return items def heapify(self, items: List[int], node_idx: int, root_idx: int = 0) -> List[int]: """ Check and fix violations of the heap property recursively """ items_count = len(items) largest_idx = node_idx # formulas for zero-indexed arrays left_child_idx = 2 * (node_idx - root_idx) + 1 + root_idx right_child_idx = 2 * (node_idx - root_idx) + 2 + root_idx # is the left child node bigger than parent node?
Top answer
1 of 6
65

Solution: Wrap data with the new comparison

Since the builtin functions don't directly support cmp functions, we need to build new variants of heapify and heappop:

from heapq import heapify, heappop
from functools import cmp_to_key

def new_heapify(data, cmp):
    s = list(map(cmp_to_key(cmp), data))
    heapify(s)
    return s

def new_heappop(data):
    return heappop(data).obj

Those are used just like your example:

>>> l = [ ['a', 3], ['b', 1] ]
>>> def foo(x, y):
...    return x[1]-y[1]
...
>>> heap = new_heapify(l, cmp=foo)
>>> new_heappop(heap)
['b', 1]

Solution: Store Augmented Tuples

A more traditional solution is to store (priority, task) tuples on the heap:

pq = [ ]
heappush(pq, (10, task1))
heappush(pq, (5, task2))
heappush(pq, (15, task3))
priority, task = heappop(pq)

This works fine as long as no two tasks have the same priority; otherwise, the tasks themselves are compared (which might not work at all in Python 3).

The regular docs give guidance on how to implement priority queues using heapq:

http://docs.python.org/library/heapq.html#priority-queue-implementation-notes

2 of 6
46

Just write an appropriate __lt__ method for the objects in the list so they sort correctly:

class FirstList(list):
    def __lt__(self, other):
        return self[0] < other[0]

lst = [ ['a', 3], ['b', 1] ]

lst = [FirstList(item) for item in lst]

Only __lt__ is needed by Python for sorting, though it's a good idea to define all of the comparisons or use functools.total_ordering.

You can see that it is working by using two items with the same first value and different second values. The two objects will swap places when you heapify no matter what the second values are because lst[0] < lst[1] will always be False. If you need the heapify to be stable, you need a more complex comparison.

Find elsewhere
🌐
Pythontic
pythontic.com › algorithms › heapq › heapify
The heapify function of heapq module in Python | Pythontic.com
The heapify() function provided by the Python module heapq creates a min heap from a Python list. The list is modified in-place as required to create a min heap.
🌐
Medium
medium.com › @hs_pedro › implementing-a-heap-in-python-1036e759e0eb
Implementing a Heap in Python. Heap is an elegant data structure that… | by Pedro Soares | Medium
December 20, 2021 - Also, we can define them as private, ... in Python does not go beyond name mangling, I will keep them private for semantic purposes. We will change the __init__ to receive a list of elements once we implement the insertion methods. Inserting a key into a heap is always a 2-step approach. First, we want to add the incoming key into the array as fast as possible, which means appending to the end. Then, we want to heapify-up (or bubble ...
🌐
Medium
cleverzone.medium.com › exploring-pythons-heapq-module-b0c9d131545c
Exploring Python's heapq Module - Cleverzone
June 17, 2024 - Priority Queue — A heap can be ... first in a min-heap). heapq.heapify(iterable) — Function is used to transform a list into a heap, in-place, in linear time....
🌐
Plain English
python.plainenglish.io › heapify-in-linear-time-114a15487ba1
Heapify in Linear Time | Python in Plain English - PlainEnglish.io
April 25, 2022 - Hence the linear time complexity for heapify! [1] https://docs.python.org/3/library/heapq.html#heapq.heapify · [2] https://youtu.be/Ch9uCBm-kUE · More content at PlainEnglish.io. Sign up for our free weekly newsletter. Follow us on Twitter and LinkedIn. Join our community Discord.
🌐
Medium
medium.com › @allan.sioson › max-heapify-build-max-heap-and-heapsort-algorithm-in-python-42c4dec70829
Max-Heapify, Build-Max-Heap, and Heapsort Algorithm | by Allan A. Sioson | Medium
October 17, 2023 - Any given array A can be transformed to a max heap by repeatedly using the Max-Heapify algorithm. Let’s call this algorithm as the Build-Max-Heap algorithm. The implementation uses the Max-Heapify algorithm starting from the last node with at least one child up to the root node. An implementation in python is given below:
🌐
FavTutor
favtutor.com › blogs › heap-in-python
Heap in Python: Min & Max Heap Implementation (with code)
April 21, 2023 - According to Official Python Docs, this module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm. The process of creating a heap data structure using the binary tree is called Heapify. The heapify ...
🌐
TutorialsPoint
tutorialspoint.com › python_data_structure › python_heaps.htm
Python - Heaps
This library has the relevant functions to carry out various operations on heap data structure. Below is a list of these functions. heapify − This function converts a regular list to a heap. In the resulting heap the smallest element gets ...
🌐
GitHub
github.com › python › cpython › blob › main › Lib › heapq.py
cpython/Lib/heapq.py at main · python/cpython
heapify(x) # transforms list into a heap, in-place, in linear time · item = heappushpop(heap, item) # pushes a new item and then returns · # the smallest item; the heap size is unchanged · item = ...
Author   python
🌐
Real Python
realpython.com › python-heapq-module
The Python heapq Module: Using Heaps and Priority Queues – Real Python
July 18, 2022 - Usually, as in the email example above, elements will be inserted into a heap one by one, starting with an empty heap. However, if there’s already a list of elements that needs to be a heap, then the Python heapq module includes heapify() for turning a list into a valid heap.
🌐
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. This module offers an efficient way to maintain a list in which you want to repeatedly access the smallest item without ...
🌐
Interviewcrunch
interviewcrunch.com › python › advanced-data-structures › heap
Heap | InterviewCrunch: Coding Interviews Broken Down
heapify() does not sort the heap, it only ensures the first/top-most item is the smallest item.