Min Heap Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn your Data Structures question into a ready to paste AI prompt, free →
Key Takeaways
- ✓Min Heap runs in O(log n) time and O(n) space, in Python as in every other language.
- ✓The heapq module operates directly on an ordinary list, there is no heap class, just functions (heappush, heappop, heapify, heapreplace, nsmallest) that maintain the invariant on a list you own.
- ✓Push tuples of (priority, tiebreaker, payload) where the tiebreaker is a monotonically increasing counter.
- ✓The Python trap: heapq supports neither a custom comparator nor decrease-key. There is no key= parameter as there is on sorted(), so the ONLY way to order by something other than natural ordering is to encode the ordering into the pushed value.
- ✓heapq is implemented in C, so heappush and heappop are fast, but heapify is the one worth knowing: building a heap from an existing list is O(n), not O(n log n), so heapify(items) beats a loop of heappush.
What Min Heap actually is
Min Heap in Python: what you actually reach for
Python implementation
import heapq
from itertools import count
class PriorityQueue:
def __init__(self) -> None:
self._heap: list[tuple[int, int, str]] = []
self._counter = count() # breaks ties so payloads are never compared
def push(self, priority: int, item: str) -> None:
heapq.heappush(self._heap, (priority, next(self._counter), item))
def pop(self) -> str:
priority, _, item = heapq.heappop(self._heap)
return item
def __len__(self) -> int:
return len(self._heap)
# O(n), not O(n log n), build in bulk rather than pushing in a loop:
data = [5, 3, 8, 1, 9, 2]
heapq.heapify(data)
print(heapq.heappop(data)) # 1
# Max-heap: negate. Top-k without a full sort:
print(heapq.nsmallest(3, data)) # O(n log k)Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(log n)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Min Heap?
The heapq module operates directly on an ordinary list, there is no heap class, just functions (heappush, heappop, heapify, heapreplace, nsmallest) that maintain the invariant on a list you own. It is a MIN-heap, which is the less common default and one of Python's conveniences here.
What is the most common Python mistake when implementing Min Heap?
heapq supports neither a custom comparator nor decrease-key. There is no key= parameter as there is on sorted(), so the ONLY way to order by something other than natural ordering is to encode the ordering into the pushed value. For a max-heap, push negated priorities; for floats that is exact, for arbitrary objects you need a wrapper class with __lt__.
How does Min Heap actually perform in Python?
heapq is implemented in C, so heappush and heappop are fast, but heapify is the one worth knowing: building a heap from an existing list is O(n), not O(n log n), so heapify(items) beats a loop of heappush. For a one-shot top-k, heapq.nsmallest(k, data) is O(n log k) and beats sorting the whole list when k is small. Time complexity is O(log n) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what GitHub Copilot offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.