TheAlgorithms/Python · error · Exception
Empty heap
Error message
Empty heap
What it means
Raised by Heap.pop() (heap/heap.py) when heap_size == 0: the if/elif chain handles sizes >= 2 and == 1, and the else raises generic Exception('Empty heap'). Popping from an empty max heap has no element to return. Note this is a bare Exception, not IndexError/ValueError, so `except IndexError` will NOT catch it — a known wart of this implementation.
Source
Thrown at data_structures/heap/heap.py:194
>>> h.extract_max()
514
>>> h = Heap()
>>> h.build_max_heap([1,2,3,4,5,6,7,8,9,0])
>>> h.extract_max()
9
"""
if self.heap_size >= 2:
me = self.h[0]
self.h[0] = self.h.pop(-1)
self.heap_size -= 1
self.max_heapify(0)
return me
elif self.heap_size == 1:
self.heap_size -= 1
return self.h.pop(-1)
else:
raise Exception("Empty heap")
def insert(self, value: T) -> None:
"""
insert a new value into the max heap
>>> h = Heap()
>>> h.insert(10)
>>> h
[10]
>>> h = Heap()
>>> h.insert(10)
>>> h.insert(10)
>>> h
[10, 10]
>>> h = Heap()
>>> h.insert(10)View on GitHub (pinned to f5988cc097)
Solutions
- Guard with emptiness check before popping: `while h.heap_size > 0: h.pop()`
- Catch the generic exception: `except Exception` — but prefer the guard, since the class is bare Exception (matches nothing narrower)
- Pop at most len elements: iterate `for _ in range(h.heap_size)`
Example fix
# before
while True:
top = h.pop() # eventually Exception('Empty heap')
# after
while h.heap_size > 0:
top = h.pop() Defensive patterns
Strategy: validation
Validate before calling
while h.heap_size > 0:
top = h.pop() Try / catch
try:
top = h.pop()
except Exception as e: # NOTE: bare Exception — not IndexError/ValueError
if str(e) != 'Empty heap':
raise
top = None Prevention
- Always bound pop loops by h.heap_size
- Never rely on `except IndexError` here — the implementation raises bare Exception
- Re-initialize the Heap between test cases instead of reusing a drained one
When it happens
Trigger: h.pop() on a fresh Heap(); popping more times than elements inserted (e.g. drain loop that pops n+1 times); popping after exceptions interrupted inserts.
Common situations: Drain loops like `while True: h.pop()`; top-N extraction where the requested N exceeds heap size; reusing a heap object across test cases without re-initialization.
Related errors
- Can't get top element for the empty heap.
- Can't get top element for the empty heap.
- Binary search tree is empty
- binary tree cannot be empty
- remove_first from empty list
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/ad9a8a95384b69db.
Report an issue: GitHub.