krahets/hello-algo · error · IndexError

索引越界

Error message

索引越界

What it means

Raised by get() in the MyList implementation when the requested index is negative or >= the current element count (_size). The check is explicit because the backing array (_arr) is pre-allocated to _capacity slots, so Python's native IndexError would not fire until the capacity boundary — hence the manual bounds check with a descriptive message '索引越界' (index out of bounds).

Source

Thrown at 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. Validate index is in [0, size()) before calling get().
  2. Use size() (not capacity()) as the loop upper bound.
  3. Switch to to_array() and use standard Python list indexing if you need slicing or negative indices.

Example fix

# before
val = nums.get(10)  # raises IndexError('索引越界') if size < 10

# after
if 0 <= index < nums.size():
    val = nums.get(index)
else:
    raise IndexError(f"Index {index} out of range for size {nums.size()}")
Defensive patterns

Strategy: validation

Validate before calling

def safe_get(nums, index):
    if not (0 <= index < nums.size()):
        raise IndexError(f"Index {index} out of range [0, {nums.size()})")
    return nums.get(index)

Type guard

def is_valid_index(nums, index: int) -> bool:
    return 0 <= index < nums.size()

Try / catch

try:
    val = nums.get(index)
except IndexError:
    val = None  # or handle the out-of-bounds case

Prevention

When it happens

Trigger: Calling nums.get(index) where index < 0 or index >= nums.size(). For example get(5) on a list with only 3 elements.

Common situations: Off-by-one loop boundaries when iterating over MyList indices. Using capacity() instead of size() as the loop upper bound. Accessing an index after elements were removed without updating cached indices.

Related errors


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