TheAlgorithms/Python · error · IndexError
peek from empty stack
Error message
peek from empty stack
What it means
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).
Source
Thrown at data_structures/stacks/stack_with_singly_linked_list.py:142
"""
if self.is_empty():
raise IndexError("pop from empty stack")
assert isinstance(self.top, Node)
pop_node = self.top
self.top = self.top.next
return pop_node.data
def peek(self) -> T:
"""
>>> stack = LinkedStack()
>>> stack.push("Java")
>>> stack.push("C")
>>> stack.push("Python")
>>> stack.peek()
'Python'
"""
if self.is_empty():
raise IndexError("peek from empty stack")
assert self.top is not None
return self.top.data
def clear(self) -> None:
"""
>>> stack = LinkedStack()
>>> stack.push("Java")
>>> stack.push("C")
>>> stack.push("Python")
>>> str(stack)
'Python->C->Java'
>>> stack.clear()
>>> len(stack) == 0
True
"""
self.top = None
View on GitHub (pinned to f5988cc097)
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
Example fix
// before
while stack.peek() != '(': # IndexError when stack drains
postfix.append(stack.pop())
# after
while stack and stack.peek() != '(':
postfix.append(stack.pop()) Defensive patterns
Strategy: validation
Validate before calling
top = stack.peek() if not stack.is_empty() else None
Try / catch
try:
top = stack.peek()
except IndexError as e:
if str(e) != 'peek from empty stack':
raise
top = None Prevention
- 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
When it happens
Trigger: peek() on a fresh LinkedStack(), or peek() in a loop condition after the stack has been drained by pop() calls.
Common situations: 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.
Related errors
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/7aa9a6aa0d3f9f3e.
Report an issue: GitHub.