krahets/hello-algo · error · IndexError

索引越界

Error message

索引越界

What it means

Raised by the get() method of a custom dynamic-array list (Traditional Chinese) when the requested index falls outside the valid range [0, _size). The list distinguishes between _size (current element count) and _capacity (allocated slot count), so accessing any index at or beyond _size — even if the underlying array has room — is rejected. This is identical to how Python's built-in list guards index access, but implemented explicitly for pedagogical purposes.

Source

Thrown at zh-hant/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 that 0 <= index < lst.size() before calling get()
  2. Use len() or size() as the loop upper bound, not capacity()
  3. Audit all index arithmetic for off-by-one errors

Example fix

# before
val = lst.get(i)  # crashes if i >= size

# after
if 0 <= i < lst.size():
    val = lst.get(i)
else:
    val = -1
Defensive patterns

Strategy: validation

Validate before calling

if 0 <= index < lst.size():
    val = lst.get(index)
else:
    raise ValueError(f"index {index} out of range [0, {lst.size()})")

Try / catch

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

Prevention

When it happens

Trigger: Calling lst.get(5) when the list holds only 3 elements; passing a negative index; computing an index from an off-by-one length calculation and using it with get().

Common situations: Looping from 0 to capacity() instead of size(); reusing an index variable after the list was shrunk by remove(); porting code from a language with 1-based indexing.

Related errors


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