TheAlgorithms/Python · error · IndexError

pop from empty stack

Error message

pop from empty stack

What it means

Raised by LinkedStack.pop() (data_structures/stacks/stack_with_singly_linked_list.py:126) when the singly-linked stack's top pointer is None. It mirrors CPython's list.pop error message deliberately, but is a manual raise after an is_empty() check. push(), peek(), and len() are the complementary API.

Source

Thrown at data_structures/stacks/stack_with_singly_linked_list.py:126

    def pop(self) -> T:
        """
        >>> stack = LinkedStack()
        >>> stack.pop()
        Traceback (most recent call last):
            ...
        IndexError: pop from empty stack
        >>> stack.push("c")
        >>> stack.push("b")
        >>> stack.push("a")
        >>> stack.pop() == 'a'
        True
        >>> stack.pop() == 'b'
        True
        >>> stack.pop() == 'c'
        True
        """
        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

View on GitHub (pinned to f5988cc097)

Solutions

  1. Guard with `if not stack.is_empty():` or `while len(stack):`
  2. Catch IndexError when using pop-until-empty as the loop terminator
  3. Audit algorithm branches so every pop() is paired with a prior push() on that path

Example fix

// before
while True:
    node = stack.pop()

# after
while stack:
    node = stack.pop()
Defensive patterns

Strategy: validation

Validate before calling

if stack.is_empty():
    return None
item = stack.pop()

Try / catch

try:
    item = stack.pop()
except IndexError as e:
    if str(e) != 'pop from empty stack':
        raise
    item = None

Prevention

When it happens

Trigger: pop() on a newly constructed LinkedStack(), or calling pop() more times than push() (the doctest pops 'a','b','c' after three pushes; a fourth pop raises).

Common situations: Delimiter-matching or backtracking algorithms that pop in loops, or state machines that pop on a branch the pushes did not cover.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/ed286cfe4f3e2a6f. Report an issue: GitHub.