TheAlgorithms/Python · error · IndexError
Can't get top element for the empty heap.
Error message
Can't get top element for the empty heap.
What it means
Raised by RandomizedHeap.top() when self._root is None, and by pop() (which calls top) — IndexError('Can't get top element for the empty heap.'). The heap is a pointer-based mergeable heap; with no root node there is no minimum to inspect, so both accessors fail fast. Using IndexError (rather than ValueError) aligns with list-style 'access empty container' semantics.
Source
Thrown at data_structures/heap/randomized_heap.py:172
"""
Return the smallest value from the heap.
>>> rh = RandomizedHeap()
>>> rh.insert(3)
>>> rh.top()
3
>>> rh.insert(1)
>>> rh.top()
1
>>> rh.insert(3)
>>> rh.top()
1
>>> rh.insert(7)
>>> rh.top()
1
"""
if not self._root:
raise IndexError("Can't get top element for the empty heap.")
return self._root.value
def clear(self) -> None:
"""
Clear the heap.
>>> rh = RandomizedHeap([3, 1, 3, 7])
>>> rh.clear()
>>> rh.pop()
Traceback (most recent call last):
...
IndexError: Can't get top element for the empty heap.
"""
self._root = None
def to_sorted_list(self) -> list[Any]:
"""
Returns sorted list containing all the values in the heap.View on GitHub (pinned to f5988cc097)
Solutions
- Check emptiness first: `if not rh.is_empty(): top = rh.top()` (or `while rh._root: ...`)
- Catch IndexError around pop/top in consumer loops
- Ensure the constructor received data: RandomizedHeap([3,1,3,7]) rather than an empty iterable
Example fix
# before rh = RandomizedHeap([]) rh.top() # IndexError # after rh = RandomizedHeap([3, 1, 3, 7]) top = rh.top() if rh._root else None
Defensive patterns
Strategy: validation
Validate before calling
top = rh.top() if rh._root is not None else None
# or guard pop loops:
while rh._root is not None:
value = rh.pop() Try / catch
try:
top = rh.top()
except IndexError:
top = None # heap drained or never filled Prevention
- Check rh._root before top()/pop()
- Remember clear() resets to empty — both methods raise afterwards
- Construct with a non-empty iterable when the heap must start populated
When it happens
Trigger: rh.top() or rh.pop() on a fresh RandomizedHeap(); the same calls after rh.clear() (the doctest shows exactly this); popping every element then popping once more.
Common situations: Peek-before-processing loops on heaps fed from possibly-empty input; calling top() after clear() in test teardown; drain loops without an emptiness condition.
Related errors
- Can't get top element for the empty heap.
- Empty heap
- Binary search tree is empty
- binary tree cannot be empty
- list index out of range.
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/0fb87560177b52b2.
Report an issue: GitHub.