{"record":{"id":"7aa9a6aa0d3f9f3e","repo":"TheAlgorithms/Python","slug":"peek-from-empty-stack","errorCode":null,"errorMessage":"peek from empty stack","messagePattern":"peek from empty stack","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"data_structures/stacks/stack_with_singly_linked_list.py","lineNumber":142,"sourceCode":"        \"\"\"\r\n        if self.is_empty():\r\n            raise IndexError(\"pop from empty stack\")\r\n        assert isinstance(self.top, Node)\r\n        pop_node = self.top\r\n        self.top = self.top.next\r\n        return pop_node.data\r\n\r\n    def peek(self) -> T:\r\n        \"\"\"\r\n        >>> stack = LinkedStack()\r\n        >>> stack.push(\"Java\")\r\n        >>> stack.push(\"C\")\r\n        >>> stack.push(\"Python\")\r\n        >>> stack.peek()\r\n        'Python'\r\n        \"\"\"\r\n        if self.is_empty():\r\n            raise IndexError(\"peek from empty stack\")\r\n\r\n        assert self.top is not None\r\n        return self.top.data\r\n\r\n    def clear(self) -> None:\r\n        \"\"\"\r\n        >>> stack = LinkedStack()\r\n        >>> stack.push(\"Java\")\r\n        >>> stack.push(\"C\")\r\n        >>> stack.push(\"Python\")\r\n        >>> str(stack)\r\n        'Python->C->Java'\r\n        >>> stack.clear()\r\n        >>> len(stack) == 0\r\n        True\r\n        \"\"\"\r\n        self.top = None\r\n\r","sourceCodeStart":124,"sourceCodeEnd":160,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/stacks/stack_with_singly_linked_list.py#L124-L160","documentation":"Raised by LinkedStack.peek() (data_structures/stacks/stack_with_singly_linked_list.py:142) when the stack is empty — peek() must return top.data but there is no top node. Unlike pop(), peek() is a non-mutating read, so this error means code inspected an empty stack, often a lookahead in a matching algorithm (e.g. peeking for '(' before popping).","triggerScenarios":"peek() on a fresh LinkedStack(), or peek() in a loop condition after the stack has been drained by pop() calls.","commonSituations":"Operator-precedence parsing loops that peek before deciding to pop — forgetting the emptiness case (`while not stack.is_empty() and stack.peek() != '('`) is the classic trigger; the sibling infix converter code in this repo does it correctly.","solutions":["Always combine the emptiness test with the peek: `while stack and stack.peek() != X:`","Pre-check is_empty() before any standalone peek()","Catch IndexError if peek is used as a speculative probe"],"exampleFix":"// before\nwhile stack.peek() != '(':  # IndexError when stack drains\n    postfix.append(stack.pop())\n\n# after\nwhile stack and stack.peek() != '(':\n    postfix.append(stack.pop())","handlingStrategy":"validation","validationCode":"top = stack.peek() if not stack.is_empty() else None","typeGuard":null,"tryCatchPattern":"try:\n    top = stack.peek()\nexcept IndexError as e:\n    if str(e) != 'peek from empty stack':\n        raise\n    top = None","preventionTips":["In precedence loops always write `while stack and stack.peek() != X:` — never peek alone","peek() does not mutate; on error the stack state is unchanged and safe to keep using"],"tags":["stack","data-structures","index-error","python"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}