{"record":{"id":"0fb87560177b52b2","repo":"TheAlgorithms/Python","slug":"can-t-get-top-element-for-the-empty-heap","errorCode":null,"errorMessage":"Can't get top element for the empty heap.","messagePattern":"Can't get top element for the empty heap\\.","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"data_structures/heap/randomized_heap.py","lineNumber":172,"sourceCode":"        \"\"\"\n        Return the smallest value from the heap.\n\n        >>> rh = RandomizedHeap()\n        >>> rh.insert(3)\n        >>> rh.top()\n        3\n        >>> rh.insert(1)\n        >>> rh.top()\n        1\n        >>> rh.insert(3)\n        >>> rh.top()\n        1\n        >>> rh.insert(7)\n        >>> rh.top()\n        1\n        \"\"\"\n        if not self._root:\n            raise IndexError(\"Can't get top element for the empty heap.\")\n        return self._root.value\n\n    def clear(self) -> None:\n        \"\"\"\n        Clear the heap.\n\n        >>> rh = RandomizedHeap([3, 1, 3, 7])\n        >>> rh.clear()\n        >>> rh.pop()\n        Traceback (most recent call last):\n            ...\n        IndexError: Can't get top element for the empty heap.\n        \"\"\"\n        self._root = None\n\n    def to_sorted_list(self) -> list[Any]:\n        \"\"\"\n        Returns sorted list containing all the values in the heap.","sourceCodeStart":154,"sourceCodeEnd":190,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/heap/randomized_heap.py#L154-L190","documentation":"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.","triggerScenarios":"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.","commonSituations":"Peek-before-processing loops on heaps fed from possibly-empty input; calling top() after clear() in test teardown; drain loops without an emptiness condition.","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"],"exampleFix":"# before\nrh = RandomizedHeap([])\nrh.top()  # IndexError\n\n# after\nrh = RandomizedHeap([3, 1, 3, 7])\ntop = rh.top() if rh._root else None","handlingStrategy":"validation","validationCode":"top = rh.top() if rh._root is not None else None\n\n# or guard pop loops:\nwhile rh._root is not None:\n    value = rh.pop()","typeGuard":null,"tryCatchPattern":"try:\n    top = rh.top()\nexcept IndexError:\n    top = None  # heap drained or never filled","preventionTips":["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"],"tags":["heap","empty-state","randomized-heap","index-error"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}