krahets/hello-algo · error · IndexError

栈为空

Error message

栈为空

What it means

IndexError '栈为空' (stack is empty) raised by ArrayStack.pop. Popping an empty stack would call list.pop() on an empty list (which itself raises a less descriptive error), so the guard intercepts with a clear message.

Source

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

        """构造方法"""
        self._stack: list[int] = []

    def size(self) -> int:
        """获取栈的长度"""
        return len(self._stack)

    def is_empty(self) -> bool:
        """判断栈是否为空"""
        return self.size() == 0

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

    def pop(self) -> int:
        """出栈"""
        if self.is_empty():
            raise IndexError("栈为空")
        return self._stack.pop()

    def peek(self) -> int:
        """访问栈顶元素"""
        if self.is_empty():
            raise IndexError("栈为空")
        return self._stack[-1]

    def to_list(self) -> list[int]:
        """返回列表用于打印"""
        return self._stack


"""Driver Code"""
if __name__ == "__main__":
    # 初始化栈
    stack = ArrayStack()

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check is_empty() before pop.
  2. Drive with while not stack.is_empty(): top = stack.pop().
  3. When matching pairs, only pop when a matching opener is expected and present.

Example fix

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

Strategy: validation

Validate before calling

def safe_pop(stack):
    return stack.pop() if not stack.is_empty() else None

Type guard

def stack_non_empty(stack) -> bool:
    return not stack.is_empty()

Try / catch

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

Prevention

When it happens

Trigger: Calling stack.pop() when the underlying list has length 0.

Common situations: Balanced-bracket / expression-evaluation code that pops a closing marker when none was pushed; recursion simulation via an explicit stack with a wrong termination test; calling pop twice for a single logical pop.

Related errors


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