krahets/hello-algo · error · IndexError

Stack is empty

Error message

Stack is empty

What it means

LinkedListStack.peek raises IndexError('Stack is empty') when size() is zero, preventing the self._peek.val dereference on a None top pointer. Because pop() calls peek() first, popping an empty stack surfaces the same exception. The guard gives a clear message and avoids an AttributeError on the None head.

Source

Thrown at en/codes/python/chapter_stack_and_queue/linkedlist_stack.py:47

    def push(self, val: int):
        """Push"""
        node = ListNode(val)
        node.next = self._peek
        self._peek = node
        self._size += 1

    def pop(self) -> int:
        """Pop"""
        num = self.peek()
        self._peek = self._peek.next
        self._size -= 1
        return num

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

    def to_list(self) -> list[int]:
        """Convert to list for printing"""
        arr = []
        node = self._peek
        while node:
            arr.append(node.val)
            node = node.next
        arr.reverse()
        return arr


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

View on GitHub (pinned to 69932aed18)

Solutions

  1. Guard the access: `if not stack.is_empty(): top = stack.peek()`.
  2. Drive drains with `while not stack.is_empty()`.
  3. Use stack.size() to bound counted loops.
  4. Wrap peek in a helper returning Optional for empty-state callers.

Example fix

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

Strategy: validation

Validate before calling

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

Type guard

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

Try / catch

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

Prevention

When it happens

Trigger: Calling peek() or pop() on an empty stack; calling after the top node was popped; unmatched push/pop in expression evaluation; drain loops that over-pop.

Common situations: DFS/recursion emulation via explicit stack; bracket matching; monotonic-stack comparisons that peek before pushing; undo inspection on an empty history.

Related errors


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