According to the example from the documentation, you can use tuples, and it will sort by the first element of the tuple:

>>> h = []
>>> heappush(h, (5, 'write code'))
>>> heappush(h, (7, 'release product'))
>>> heappush(h, (1, 'write spec'))
>>> heappush(h, (3, 'create tests'))
>>> heappop(h)
(1, 'write spec')

So if you don't want to (or can't?) do a __cmp__ method, you can manually extract your sorting key at push time.

Note that if the first elements in a pair of tuples are equal, further elements will be compared. If this is not what you want, you need to ensure that each first element is unique.

Answer from Jander on Stack Overflow
🌐
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 › python-heapq-heappush-method
Python heapq.heappush() Method - GeeksforGeeks
June 11, 2026 - DSA Python · Data Science · NumPy · Pandas · Practice · Django · Flask · Last Updated : 11 Jun, 2026 · heapq.heappush() function inserts an element into a heap while maintaining the heap property.
🌐
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. It allows for efficient management of priority queues in a way that elements with higher priority are served ...
🌐
W3Schools
w3schools.com › python › ref_module_heapq.asp
Python heapq Module
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python 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 range(3)]) Try it Yourself »
🌐
GeeksforGeeks
geeksforgeeks.org › python › heap-queue-or-heapq-in-python
Heap queue or heapq in Python - GeeksforGeeks
Explanation: heappushpop(h, 5) first pushes 5 into the heap and immediately pops the smallest element (which is also 5).
Published   April 6, 2026
🌐
Python Cheat Sheet
pythonsheets.com › notes › basic › python-heap.html
Heap — Python Cheat Sheet
>>> import heapq >>> # Convert list to heap in-place >>> h = [5, 1, 3, 2, 6] >>> heapq.heapify(h) >>> h[0] # smallest element at root 1 >>> # Push and pop >>> heapq.heappush(h, 0) >>> heapq.heappop(h) 0 >>> # Push and pop in one operation >>> heapq.heappushpop(h, 4) # push 4, then pop smallest 1 >>> # Pop and push in one operation >>> heapq.heapreplace(h, 0) # pop smallest, then push 0 2
Find elsewhere
Top answer
1 of 6
98

heapq is a binary heap, with O(log n) push and O(log n) pop. See the heapq source code.

The algorithm you show takes O(n log n) to push all the items onto the heap, and then O((n-k) log n) to find the kth largest element. So the complexity would be O(n log n). It also requires O(n) extra space.

You can do this in O(n log k), using O(k) extra space by modifying the algorithm slightly. I'm not a Python programmer, so you'll have to translate the pseudocode:

# create a new min-heap
# push the first k nums onto the heap
for the rest of the nums:
    if num > heap.peek()
        heap.pop()
        heap.push(num)

# at this point, the k largest items are on the heap.
# The kth largest is the root:

return heap.pop()

The key here is that the heap contains just the largest items seen so far. If an item is smaller than the kth largest seen so far, it's never put onto the heap. The worst case is O(n log k).

Actually, heapq has a heapreplace method, so you could replace this:

    if num > heap.peek()
        heap.pop()
        heap.push(num)

with

    if num > heap.peek()
        heap.replace(num)

Also, an alternative to pushing the first k items is to create a list of the first k items and call heapify. A more optimized (but still O(n log k)) algorithm is:

# create array of first `k` items
heap = heapify(array)
for remaining nums
    if (num > heap.peek())
        heap.replace(num)
return heap.pop()

You could also call heapify on the entire array, then pop the first n-k items, and then take the top:

heapify(nums)
for i = 0 to n-k
    heapq.heappop(nums)
return heapq.heappop(nums)

That's simpler. Not sure if it's faster than my previous suggestion, but it modifies the original array. The complexity is O(n) to build the heap, then O((n-k) log n) for the pops. So it's be O((n-k) log n). Worst case O(n log n).

2 of 6
16

heapify() actually takes linear time because the approach is different than calling heapq.push() N times.

heapq.push()/heapq.pop() takes log n time because it adjust all the nodes at a given hight/level.

when you pass an array in heapify() it makes sure that the left and right children of the node are already maintaining the heap property whether it is a min heap or max heap.

you can see this video: https://www.youtube.com/watch?v=HqPJF2L5h9U

https://www.youtube.com/watch?v=B7hVxCmfPtM

Hope this would help.

🌐
Python Module of the Week
pymotw.com › 2 › heapq
heapq – In-place heap sort algorithm - Python Module of the Week
import heapq from heapq_showtree import show_tree from heapq_heapdata import data heap = [] print 'random :', data print for n in data: print 'add =:' % n heapq.heappush(heap, n) show_tree(heap) $ python heapq_heappush.py random : [19, 9, 4, 10, 11, 8, 2] add 19: 19 ------------------------------------ add 9: 9 19 ------------------------------------ add 4: 4 19 9 ------------------------------------ add 10: 4 10 9 19 ------------------------------------ add 11: 4 10 9 19 11 ------------------------------------ add 8: 4 10 8 19 11 9 ------------------------------------ add 2: 2 10 4 19 11 9 8 ------------------------------------
🌐
7-Zip Documentation
documentation.help › Python-3.6.4 › heapq.html
8.5. heapq — Heap queue algorithm - Python 3.6.4 Documentation
December 19, 2017 - pq = [] # list of entries arranged in a heap entry_finder = {} # mapping of tasks to entries REMOVED = '<removed-task>' # placeholder for a removed task counter = itertools.count() # unique sequence count def add_task(task, priority=0): 'Add a new task or update the priority of an existing task' if task in entry_finder: remove_task(task) count = next(counter) entry = [priority, count, task] entry_finder[task] = entry heappush(pq, entry) def remove_task(task): 'Mark an existing task as REMOVED.
🌐
GitHub
github.com › python › cpython › blob › main › Lib › heapq.py
cpython/Lib/heapq.py at main · python/cpython
item = heappushpop(heap, item) # pushes a new item and then returns · # the smallest item; the heap size is unchanged · item = heapreplace(heap, item) # pops and returns smallest item, and adds ·  ...
Author   python
🌐
Medium
medium.com › data-science › introduction-to-python-heapq-module-53534feda625
Introduction to Python Heapq Module | by Vijini Mallawaarachchi | TDS Archive | Medium
May 6, 2020 - Assuming that you know how the heap data structure works, let’s see what functions are provided by Python’s heapq model. heappush(heap, item) — Push the value item into the heap
🌐
MicroPython
docs.micropython.org › en › latest › library › heapq.html
heapq – heap queue algorithm — MicroPython latest documentation
heapq.heappush(heap, item) · Push the item onto the heap. heapq.heappop(heap) · Pop the first item from the heap, and return it. Raise IndexError if heap is empty. The returned item will be the smallest item in the heap. heapq.heapify(x) · Convert the list x into a heap.
🌐
Educative
educative.io › answers › what-is-the-heapqheappushpop-method-in-python
What is the heapq.heappushpop() method in Python?
Note: To understand more about heaps and priority queues, please refer to What is a Heap? and What is the Python priority queue? The heappushpop method inserts a given item to the heap and then pops the smallest element from the heap.
🌐
Developer-service
developer-service.blog › understanding-pythons-heapq-module
Understanding Python's heapq Module
September 19, 2024 - import heapq heap = [] heapq.heappush(heap, 10) heapq.heappush(heap, 5) heapq.heappush(heap, 20) After these operations, heap will be [5, 10, 20], with the smallest element at index 0. The smallest element can be accessed without removing it by simply referencing heap[0]: ... After this operation, the heap automatically adjusts, and the next smallest element takes the root position. If you already have a list of elements, you can convert it into a heap using heapq.heapify(): ... Solutions Architect · Senior Python & AI Engineer ·
🌐
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) # Output: Heap after insertion: [4, 9, 6] # Delete the smallest element from the heap heapq.heappop(heap) print("Heap after deletion: ", heap) # Output: Heap after deletion: [6, 9] # Extract the smallest element smallest = heapq.nsmallest(1, heap)[0] print("Smallest element in the heap: ", smallest) # Output: Smallest element in the heap: 6 ·
🌐
GitHub
gist.github.com › 224175
[Python][library] simple heapq implementation · GitHub
[Python][library] simple heapq implementation. GitHub Gist: instantly share code, notes, and snippets.