krahets/hello-algo · error · IndexError

индекс выходит за границы

Error message

индекс выходит за границы

What it means

This IndexError (Russian: 'индекс выходит за границы' = 'index out of bounds') is raised by MyList.get(index) (my_list.py:30, ru translation) when index < 0 or index >= self._size. MyList keeps the live element count in _size distinct from the backing array capacity, so it must validate bounds itself. get() performs no resizing and is a pure read, so the guard is the only protection against reading uninitialized backing slots.

Source

Thrown at ru/codes/python/chapter_array_and_linkedlist/my_list.py:30

        """Конструктор"""
        self._capacity: int = 10  # Вместимость списка
        self._arr: list[int] = [0] * self._capacity  # Массив (для хранения элементов списка)
        self._size: int = 0  # Длина списка (текущее число элементов)
        self._extend_ratio: int = 2  # Коэффициент увеличения списка при каждом расширении

    def size(self) -> int:
        """Получить длину списка (текущее число элементов)"""
        return self._size

    def capacity(self) -> int:
        """Получить вместимость списка"""
        return self._capacity

    def get(self, index: int) -> int:
        """Доступ к элементу"""
        # Если индекс выходит за границы, выбрасывается исключение; далее аналогично
        if index < 0 or index >= self._size:
            raise IndexError("индекс выходит за границы")
        return self._arr[index]

    def set(self, num: int, index: int):
        """Обновление элемента"""
        if index < 0 or index >= self._size:
            raise IndexError("индекс выходит за границы")
        self._arr[index] = num

    def add(self, num: int):
        """Добавление элемента в конец"""
        # При превышении вместимости по числу элементов запускается расширение
        if self.size() == self.capacity():
            self.extend_capacity()
        self._arr[self._size] = num
        self._size += 1

    def insert(self, num: int, index: int):
        """Вставка элемента в середину"""

View on GitHub (pinned to 69932aed18)

Solutions

  1. Pre-validate `0 <= index < lst.size()` before get().
  2. Loop `for i in range(lst.size())` (exclusive upper bound), not size()+1.
  3. Re-derive any cached index after mutations that change _size.
  4. Use to_array() and Python's own list indexing if you need negative-index or slicing semantics.

Example fix

// before
for i in range(lst.size() + 1):
    x = lst.get(i)  # IndexError at i == size()

// after
for i in range(lst.size()):
    x = lst.get(i)
Defensive patterns

Strategy: validation

Validate before calling

if 0 <= index < lst.size():
    val = lst.get(index)
# use size(), not capacity() — capacity (10) != element count

Type guard

def valid_get_index(lst: MyList, index: int) -> bool:
    return isinstance(index, int) and 0 <= index < lst.size()

Try / catch

try:
    val = lst.get(index)
except IndexError:
    val = None

Prevention

When it happens

Trigger: Calling get(index) with index outside [0, size). Reading get(size()) — the classic off-by-one (valid range is 0..size-1). Passing a negative index. Indexing by a value derived from capacity (10) rather than current size.

Common situations: Off-by-one loops `for i in range(size()+1)` that overshoot. Confusing capacity with size when the list is partially filled. Stale index after add/insert/remove changed _size. Using get() on an empty list.

Related errors


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