Define a class, in which override the __lt__() function. See example below (works in Python 3.7):

import heapq

class Node(object):
    def __init__(self, val: int):
        self.val = val

    def __repr__(self):
        return f'Node value: {self.val}'

    def __lt__(self, other):
        return self.val < other.val

heap = [Node(2), Node(0), Node(1), Node(4), Node(2)]
heapq.heapify(heap)
print(heap)  # output: [Node value: 0, Node value: 2, Node value: 1, Node value: 4, Node value: 2]

heapq.heappop(heap)
print(heap)  # output: [Node value: 1, Node value: 2, Node value: 2, Node value: 4]

Answer from Fanchen Bao on Stack Overflow
Top answer
1 of 10
184

Define a class, in which override the __lt__() function. See example below (works in Python 3.7):

import heapq

class Node(object):
    def __init__(self, val: int):
        self.val = val

    def __repr__(self):
        return f'Node value: {self.val}'

    def __lt__(self, other):
        return self.val < other.val

heap = [Node(2), Node(0), Node(1), Node(4), Node(2)]
heapq.heapify(heap)
print(heap)  # output: [Node value: 0, Node value: 2, Node value: 1, Node value: 4, Node value: 2]

heapq.heappop(heap)
print(heap)  # output: [Node value: 1, Node value: 2, Node value: 2, Node value: 4]

2 of 10
174

According to the heapq documentation, the way to customize the heap order is to have each element on the heap to be a tuple, with the first tuple element being one that accepts normal Python comparisons.

The functions in the heapq module are a bit cumbersome (since they are not object-oriented), and always require our heap object (a heapified list) to be explicitly passed as the first parameter. We can kill two birds with one stone by creating a very simple wrapper class that will allow us to specify a key function, and present the heap as an object.

The class below keeps an internal list, where each element is a tuple, the first member of which is a key, calculated at element insertion time using the key parameter, passed at Heap instantiation:

# -*- coding: utf-8 -*-
import heapq

class MyHeap(object):
    def __init__(self, initial=None, key=lambda x:x):
        self.key = key
        self.index = 0
        if initial:
            self._data = [(key(item), i, item) for i, item in enumerate(initial)]
            self.index = len(self._data)
            heapq.heapify(self._data)
        else:
            self._data = []

    def push(self, item):
        heapq.heappush(self._data, (self.key(item), self.index, item))
        self.index += 1

    def pop(self):
        return heapq.heappop(self._data)[2]

(The extra self.index part is to avoid clashes when the evaluated key value is a draw and the stored value is not directly comparable - otherwise heapq could fail with TypeError)

🌐
Python.org
discuss.python.org › ideas
Create new package similar to `heapq` but be able to pass custom comparator through a constructor - Ideas - Discussions on Python.org
November 23, 2024 - The current heap container is okay in Python. It works as intended but you cannot pass a custom comparator and working with it feels “C like”, since you need to pass your list object each time.
Discussions

Title: Add Optional Comparator Support to heapq for Enhanced Flexibility
Currently, the heapq module in CPython uses a fixed implementation based on the default comparison behavior of Python objects. However, this design restricts the usability of heapq in scenarios where users need a custom ordering for their data. More on github.com
🌐 github.com
6
November 27, 2024
How to make custom comparator for heapq

You could have a class that derives heapq, then use the correct dunder methods.

class PriorityQ(heapq):
    ...
    def __gt__(self, other):
        # your comparison logic for greater than

There are methods like this that work in the same way as operators in C++. This code will be the same as overloading operator>.

More on reddit.com
🌐 r/learnpython
2
1
September 24, 2023
python - heapq custom compareTo - Stack Overflow
I'm trying to define a custome method to make an ordered insert into a priority queue in python but not getting the expected results. Once defined the insert method into the queue like the followin... More on stackoverflow.com
🌐 stackoverflow.com
heap - Custom comparator in Python - Stack Overflow
I'm trying to write a custom comparator in Python, that compares two node objects based on the following rules 1. Least frequency 2. Shortest length 3. Lexicographic ordering. Here's my node object More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › heapq-with-custom-predicate-in-python
Heapq with custom predicate in Python - GeeksforGeeks
July 23, 2025 - The heapq module functions can take either a list of items or a list of tuples as a parameter. Thus, there are two ways to customize the sorting process: Convert the iterable to a list of tuples/list for comparison.
🌐
GitHub
github.com › python › cpython › issues › 127328
Title: Add Optional Comparator Support to heapq for Enhanced Flexibility · Issue #127328 · python/cpython
November 27, 2024 - Proposal Introduce an optional comparator parameter to the heapq module to allow greater flexibility in heap operations. This would eliminate the need for users to create additional wrapper objects or manage unnecessary cognitive overhead for ...
Author   python
🌐
GitHub
gist.github.com › sansyrox › 105e37efb01b864bbc99b2338ae91fde
Custom Comparators in Python heap · GitHub
Custom Comparators in Python heap. GitHub Gist: instantly share code, notes, and snippets.
🌐
Linux Hint
linuxhint.com › python-heapq-custom-comparator
Linux Hint – Linux Hint
Linux Hint LLC, [email protected] 1210 Kelly Park Circle, Morgan Hill, CA 95037 Privacy Policy and Terms of Use
Find elsewhere
🌐
Python Pool
pythonpool.com › home › blog › python heapq: boost your efficiency with heap operations!
Python Heapq: Boost Your Efficiency with Heap Operations!
May 30, 2023 - So, it is a custom comparator that does not use the default heapq.bucket_by_key function, but instead uses a custom one.
🌐
HatchJS
hatchjs.com › home › python heapq: how to create a custom comparator
Python heapq: How to create a custom comparator
January 5, 2024 - To create a heapq custom comparator, you need to create a function that takes two arguments, `a` and `b`, and returns a negative integer if `a` should be less than `b`, a positive integer if `a` should be greater than `b`, or 0 if `a` and `b` are equal...
🌐
GitHub
github.com › nwthomas › heapq
GitHub - nwthomas/heapq: TypeScript implementation of the CPython heapq module · GitHub
A custom comparator function can be provided in an options object to perform max heap comparisons or to operate on more complex data types: import { heapPushPop } from "@nwthomas/heapq/heapPushPop"; const heap = [20, 5, 10]; const result = ...
Author   nwthomas
🌐
TheLinuxCode
thelinuxcode.com › home › python heapq custom comparator
Python Heapq Custom Comparator – TheLinuxCode
December 27, 2023 - To summarize, the Python heapq module provides efficient heap and priority queue implementation that can be extremely useful for sorting with custom ordering logic. Overriding comparison operators either via key functions or the lt method allows flexibly adapting heapq for different data types.
🌐
CSDN
devpress.csdn.net › python › 62fd284ac677032930802dc2.html
heapq with custom compare predicate_python_Mangs-Python
August 18, 2022 - # -*- coding: utf-8 -*- import heapq class MyHeap(object): def __init__(self, initial=None, key=lambda x:x): self.key = key self.index = 0 if initial: self._data = [(key(item), i, item) for i, item in enumerate(initial)] self.index = len(self._data) heapq.heapify(self._data) else: self._data = [] def push(self, item): heapq.heappush(self._data, (self.key(item), self.index, item)) self.index += 1 def pop(self): return heapq.heappop(self._data)[2] (The extra self.index part is to avoid clashes when the evaluated key value is a draw and the stored value is not directly comparable - otherwise heapq could fail with TypeError)
🌐
Codemia
codemia.io › knowledge-hub › path › heapq_with_custom_compare_predicate
heapq with custom compare predicate
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises
🌐
Stack Abuse
stackabuse.com › guide-to-heaps-in-python
Guide to Heaps in Python
April 18, 2024 - It's essential to note that the heapq module creates min heaps by default. This means that the smallest element is always at the root (or the first position in the list). If you need a max heap, you'd have to invert order by multiplying elements by -1 or use a custom comparison function. Python's heapq module provides a suite of functions that allow developers to perform various heap operations on lists.
🌐
LeetCode
leetcode.com › discuss › general-discussion › 661156 › max-heaps-ordered-heaps-in-python-with-custom-comparators-and-key-function
Max Heaps, Ordered Heaps in Python With Custom Comparators and Key Function - Discuss - LeetCode
May 30, 2020 - I have made a single heap class ... You can use a comparator function if you want to structure your heap according to one or more parameters(For Example you want the highest value closest to an index).
🌐
Frederick-s
frederick-s.github.io › 2021 › 07 › 31 › python-heapq-custom-comparator
Python heapq 自定义比较器 | Übung macht den Meister
July 31, 2021 - 使用 Python 的 heapq 模块时,如果处理的是较为复杂的数据结构,则需要实现自定义比较器来比较两个元素的大小。 使用元组 如果 heapq 中放入的是元组,那么元组的第一个元素会用于大小比较。假设有这样一个问题,给定一个数组,返回前 k 小的数字所在数组中的位置。Top k 的问题的一个解法是使用堆,但是这里要求的是数字在数组中的位置而不是数字本身,所以不能直接将数组堆化,可以先将数组