krahets/hello-algo · error · IndexError

Stack is empty

Error message

Stack is empty

What it means

ArrayStack.pop raises IndexError('Stack is empty') when size() is zero, preventing list.pop() from raising its own opaque IndexError on the empty backing list. The explicit guard gives a domain-meaningful message. It encodes the LIFO contract that you cannot pop what was never pushed.

Source

Thrown at en/codes/python/chapter_stack_and_queue/array_stack.py:30

        """Constructor"""
        self._stack: list[int] = []

    def size(self) -> int:
        """Get the length of the stack"""
        return len(self._stack)

    def is_empty(self) -> bool:
        """Check if the stack is empty"""
        return self.size() == 0

    def push(self, item: int):
        """Push"""
        self._stack.append(item)

    def pop(self) -> int:
        """Pop"""
        if self.is_empty():
            raise IndexError("Stack is empty")
        return self._stack.pop()

    def peek(self) -> int:
        """Access top of the stack element"""
        if self.is_empty():
            raise IndexError("Stack is empty")
        return self._stack[-1]

    def to_list(self) -> list[int]:
        """Return list for printing"""
        return self._stack


"""Driver Code"""
if __name__ == "__main__":
    # Initialize stack
    stack = ArrayStack()

View on GitHub (pinned to 69932aed18)

Solutions

  1. Guard the pop: `if not stack.is_empty(): top = stack.pop()`.
  2. Drive drains with the predicate: `while not stack.is_empty(): x = stack.pop()`.
  3. Use stack.size() to bound counted loops.
  4. Ensure every pop is preceded by a matching push in paired-traversal algorithms.

Example fix

// before
top = stack.pop()  # raises if empty
// after
if not stack.is_empty():
    top = stack.pop()
else:
    top = None
Defensive patterns

Strategy: validation

Validate before calling

if not stack.is_empty():
    top = stack.pop()

Type guard

def stack_nonempty(s) -> bool:
    return not s.is_empty()

Try / catch

try:
    top = stack.pop()
except IndexError:
    top = None

Prevention

When it happens

Trigger: Calling pop() on a brand-new stack; calling pop() after the last element was popped; unmatched push/pop pairing in expression evaluation or recursion emulation; drain loops that over-pop.

Common situations: Bracket/parenthesis matching that pops on every closer; DFS emulation via explicit stack; undo stacks drained past empty; mismatched push/pop counts in parsers.

Related errors


AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13). Data as JSON: /api/errors/82feeecf1bdaca2b. Report an issue: GitHub.