krahets/hello-algo · error · IndexError
堆疊為空
Error message
堆疊為空
What it means
Raised by the pop() method of an array-backed stack when size() returns 0. The stack delegates to Python's built-in list.append/pop for storage but adds an explicit emptiness guard before calling self._stack.pop(). This provides a descriptive error message instead of Python's generic 'pop from empty list'.
Source
Thrown at zh-hant/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
- Check stack.is_empty() before calling pop()
- Use while not stack.is_empty() as the draining loop condition
- Wrap in try/except IndexError for defensive stack operations
Example fix
# before
val = stack.pop()
# after
if not stack.is_empty():
val = stack.pop()
else:
val = None Defensive patterns
Strategy: validation
Validate before calling
if not stack.is_empty():
val = stack.pop()
else:
val = None Try / catch
try:
val = stack.pop()
except IndexError:
val = None Prevention
- Check is_empty() before pop() in all stack-draining loops
- Use while not stack.is_empty() as the loop condition
- Track the number of push() calls for batch pop() operations
When it happens
Trigger: Calling pop() on a newly constructed ArrayStack; calling pop() more times than push() in a processing loop; draining the stack in a while loop without checking is_empty().
Common situations: Expression-evaluation or backtracking algorithms that pop past empty; undo/redo stacks where redo is called with nothing to redo; testing boundary conditions with empty stacks.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/cab1767f666f8726.
Report an issue: GitHub.