krahets/hello-algo · error · IndexError
スタックが空です
Error message
スタックが空です
What it means
This IndexError (Japanese: 'スタックが空です' = 'stack is empty') is raised by ArrayStack.pop() (array_stack.py:30) when size() == 0. ArrayStack wraps a Python list; the guard prevents calling list.pop() on an empty backing list (which would itself raise IndexError with a different message). push() is unbounded (list.append grows dynamically), so 'full' is never an issue here.
Source
Thrown at ja/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 `if not stack.is_empty(): stack.pop()`.
- Loop with `while not stack.is_empty():` for full drain.
- Track expected depth separately and never pop below it.
- Use try/except IndexError if pop-on-empty is a benign case in your algorithm.
Example fix
// before top = stack.pop() # IndexError when empty // after top = stack.pop() if not stack.is_empty() else None
Defensive patterns
Strategy: validation
Validate before calling
if not stack.is_empty():
top = stack.pop() Type guard
def stack_has_top(stack: ArrayStack) -> bool:
return not stack.is_empty() Try / catch
try:
top = stack.pop()
except IndexError:
top = None Prevention
- Guard every pop() with is_empty().
- Drain with `while not stack.is_empty():`.
- Track push/pop balance in expression evaluators and backtracking.
- push() is unbounded (list.append), so only underflow, never overflow, can occur.
When it happens
Trigger: Calling pop() on a freshly constructed ArrayStack (empty list). Calling pop() more times than push(). Popping in a loop without an is_empty() check.
Common situations: Unbalanced push/pop in expression evaluation or backtracking. Draining the stack to empty then popping once more. Assuming a prior push succeeded when it actually was skipped by upstream logic.
Related errors
AI-assisted analysis of krahets/hello-algo@69932aed18 (2026-08-13).
Data as JSON: /api/errors/0c190a945dd30351.
Report an issue: GitHub.