{"record":{"id":"f08448aa9111c04c","repo":"krahets/hello-algo","slug":"error-f08448","errorCode":null,"errorMessage":"索引越界","messagePattern":"索引越界","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"codes/python/chapter_array_and_linkedlist/my_list.py","lineNumber":30,"sourceCode":"        \"\"\"构造方法\"\"\"\n        self._capacity: int = 10  # 列表容量\n        self._arr: list[int] = [0] * self._capacity  # 数组（存储列表元素）\n        self._size: int = 0  # 列表长度（当前元素数量）\n        self._extend_ratio: int = 2  # 每次列表扩容的倍数\n\n    def size(self) -> int:\n        \"\"\"获取列表长度（当前元素数量）\"\"\"\n        return self._size\n\n    def capacity(self) -> int:\n        \"\"\"获取列表容量\"\"\"\n        return self._capacity\n\n    def get(self, index: int) -> int:\n        \"\"\"访问元素\"\"\"\n        # 索引如果越界，则抛出异常，下同\n        if index < 0 or index >= self._size:\n            raise IndexError(\"索引越界\")\n        return self._arr[index]\n\n    def set(self, num: int, index: int):\n        \"\"\"更新元素\"\"\"\n        if index < 0 or index >= self._size:\n            raise IndexError(\"索引越界\")\n        self._arr[index] = num\n\n    def add(self, num: int):\n        \"\"\"在尾部添加元素\"\"\"\n        # 元素数量超出容量时，触发扩容机制\n        if self.size() == self.capacity():\n            self.extend_capacity()\n        self._arr[self._size] = num\n        self._size += 1\n\n    def insert(self, num: int, index: int):\n        \"\"\"在中间插入元素\"\"\"","sourceCodeStart":12,"sourceCodeEnd":48,"githubUrl":"https://github.com/krahets/hello-algo/blob/69932aed1891a7b7f6a0de88cd116d3fe13e7032/codes/python/chapter_array_and_linkedlist/my_list.py#L12-L48","documentation":"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).","triggerScenarios":"Calling nums.get(index) where index < 0 or index >= nums.size(). For example get(5) on a list with only 3 elements.","commonSituations":"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.","solutions":["Validate index is in [0, size()) before calling get().","Use size() (not capacity()) as the loop upper bound.","Switch to to_array() and use standard Python list indexing if you need slicing or negative indices."],"exampleFix":"# before\nval = nums.get(10)  # raises IndexError('索引越界') if size < 10\n\n# after\nif 0 <= index < nums.size():\n    val = nums.get(index)\nelse:\n    raise IndexError(f\"Index {index} out of range for size {nums.size()}\")","handlingStrategy":"validation","validationCode":"def safe_get(nums, index):\n    if not (0 <= index < nums.size()):\n        raise IndexError(f\"Index {index} out of range [0, {nums.size()})\")\n    return nums.get(index)","typeGuard":"def is_valid_index(nums, index: int) -> bool:\n    return 0 <= index < nums.size()","tryCatchPattern":"try:\n    val = nums.get(index)\nexcept IndexError:\n    val = None  # or handle the out-of-bounds case","preventionTips":["Use size() (not capacity()) as the loop upper bound.","Cache size() only if no intervening mutations occur.","Prefer to_array() with native slicing for iteration-heavy code."],"tags":["python","list","index-error","bounds-check"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}