{"record":{"id":"8dafa2ac7ae403c7","repo":"krahets/hello-algo","slug":"error-8dafa2","errorCode":null,"errorMessage":"索引越界","messagePattern":"索引越界","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"zh-hant/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/zh-hant/codes/python/chapter_array_and_linkedlist/my_list.py#L12-L48","documentation":"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.","triggerScenarios":"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().","commonSituations":"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.","solutions":["Validate that 0 <= index < lst.size() before calling get()","Use len() or size() as the loop upper bound, not capacity()","Audit all index arithmetic for off-by-one errors"],"exampleFix":"# before\nval = lst.get(i)  # crashes if i >= size\n\n# after\nif 0 <= i < lst.size():\n    val = lst.get(i)\nelse:\n    val = -1","handlingStrategy":"validation","validationCode":"if 0 <= index < lst.size():\n    val = lst.get(index)\nelse:\n    raise ValueError(f\"index {index} out of range [0, {lst.size()})\")","typeGuard":null,"tryCatchPattern":"try:\n    val = lst.get(index)\nexcept IndexError:\n    val = -1","preventionTips":["Always use size() as the loop upper bound, never capacity()","Validate externally-computed indices before passing to get()","Remember that capacity() >= size(); slots between them are inaccessible"],"tags":["data-structure","dynamic-array","python","index-bounds"],"backgroundTag":null,"analyzedSha":"69932aed1891a7b7f6a0de88cd116d3fe13e7032","analyzedAt":"2026-08-13T23:02:37.581Z","schemaVersion":2},"datasetVersion":"2026-08-14T00:17:13.853Z"}