krahets/hello-algo · error · IndexError

стек пуст

Error message

стек пуст

What it means

Raised by the peek() method of a singly-linked-list-based stack (Russian translation) when the stack has zero elements. Since pop() calls peek() internally to retrieve the top value before unlinking it, both operations trigger this error on an empty stack. The guard uses is_empty(), which returns true when the _peek pointer is None or _size equals 0.

Source

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

    def push(self, val: int):
        """Поместить в стек"""
        node = ListNode(val)
        node.next = self._peek
        self._peek = node
        self._size += 1

    def pop(self) -> int:
        """Извлечь из стека"""
        num = self.peek()
        self._peek = self._peek.next
        self._size -= 1
        return num

    def peek(self) -> int:
        """Доступ к верхнему элементу стека"""
        if self.is_empty():
            raise IndexError("стек пуст")
        return self._peek.val

    def to_list(self) -> list[int]:
        """Преобразовать в список для вывода"""
        arr = []
        node = self._peek
        while node:
            arr.append(node.val)
            node = node.next
        arr.reverse()
        return arr


"""Driver Code"""
if __name__ == "__main__":
    # Инициализация стека
    stack = LinkedListStack()

View on GitHub (pinned to 69932aed18)

Solutions

  1. Check stack.is_empty() before calling peek() or pop()
  2. Ensure push and pop call counts are balanced inside loops
  3. Wrap the operation in try/except IndexError for defensive handling

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()
# or equivalently:
if stack.size() > 0:
    val = stack.peek()

Try / catch

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

Prevention

When it happens

Trigger: Calling peek() or pop() on a freshly constructed LinkedListStack with no prior push() calls; calling pop() more times than push() in a processing loop; draining the stack to completion and then attempting one more access.

Common situations: Bracket-matching or expression-evaluation parsers that pop after input is exhausted; recursive-call simulators that pop more frames than were pushed; testing edge cases with empty input arrays passed to stack-based algorithms.

Related errors


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