krahets/hello-algo · error · IndexError

стек пуст

Error message

стек пуст

What it means

Raised by ArrayStack.pop() in chapter_stack_and_queue/array_stack.py:30 — IndexError("стек пуст" = "stack is empty"). ArrayStack wraps a Python list; pop() delegates to list.pop after an explicit is_empty() check, giving a localized Russian message instead of Python's generic "pop from empty list".

Source

Thrown at ru/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. Guard: if not stk.is_empty(): stk.pop().
  2. Use is_empty() as the loop/termination condition.
  3. Wrap pop in try/except IndexError for optional unwinding.
  4. Ensure every code path that pops has a matching push on the same logical scope.

Example fix

// before
x = stk.pop()
// after
x = stk.pop() if not stk.is_empty() else None
Defensive patterns

Strategy: validation

Validate before calling

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

Type guard

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

Try / catch

try:
    x = stk.pop()
except IndexError:
    x = None

Prevention

When it happens

Trigger: Calling pop() on a fresh or fully drained stack. More pops than pushes. Recursive/unwinding code that pops per frame without an empty guard.

Common situations: Mismatched push/pop in parsing or backtracking. Reusing a stack object across operations without clearing checks. Edge case where input triggers zero pushes.

Related errors


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