{"record":{"id":"68acdf5ccccd04e2","repo":"TheAlgorithms/Python","slug":"list-index-out-of-range-68acdf","errorCode":null,"errorMessage":"list index out of range.","messagePattern":"list index out of range\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"data_structures/linked_list/singly_linked_list.py","lineNumber":126,"sourceCode":"    def __getitem__(self, index: int) -> Any:\n        \"\"\"\n        Indexing Support. Used to get a node at particular position\n        >>> linked_list = LinkedList()\n        >>> for i in range(0, 10):\n        ...     linked_list.insert_nth(i, i)\n        >>> all(str(linked_list[i]) == str(i) for i in range(0, 10))\n        True\n        >>> linked_list[-10]\n        Traceback (most recent call last):\n            ...\n        ValueError: list index out of range.\n        >>> linked_list[len(linked_list)]\n        Traceback (most recent call last):\n            ...\n        ValueError: list index out of range.\n        \"\"\"\n        if not 0 <= index < len(self):\n            raise ValueError(\"list index out of range.\")\n        for i, node in enumerate(self):\n            if i == index:\n                return node\n        return None\n\n    # Used to change the data of a particular node\n    def __setitem__(self, index: int, data: Any) -> None:\n        \"\"\"\n        >>> linked_list = LinkedList()\n        >>> for i in range(0, 10):\n        ...     linked_list.insert_nth(i, i)\n        >>> linked_list[0] = 666\n        >>> linked_list[0]\n        666\n        >>> linked_list[5] = -666\n        >>> linked_list[5]\n        -666\n        >>> linked_list[-10] = 666","sourceCodeStart":108,"sourceCodeEnd":144,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/linked_list/singly_linked_list.py#L108-L144","documentation":"LinkedList.__getitem__ raises ValueError('list index out of range.') for index outside [0, len). Note the type is ValueError, not the IndexError CPython lists raise — a deliberate quirk of this class; match on the class's behavior, not the builtin's.","triggerScenarios":"linked_list[-1] (negative indices are NOT supported), linked_list[len(linked_list)], or any index on an empty list.","commonSituations":"Porting list/tuple indexing code that relies on negative indices; loops using range(len+1) off by one; catching IndexError in caller code and having this ValueError slip through.","solutions":["Validate 0 <= index < len(linked_list) before subscripting.","Emulate negative indices yourself: index = index if index >= 0 else len(linked_list) + index, then bounds-check.","In callers, catch ValueError for this class's subscripts, not IndexError."],"exampleFix":"# before\nlast = linked_list[-1]  # ValueError: list index out of range.\n# after\nlast = linked_list[len(linked_list) - 1] if len(linked_list) else None","handlingStrategy":"validation","validationCode":"def get(ll, index, default=None):\n    if 0 <= index < len(ll):\n        return ll[index]\n    if -len(ll) <= index < 0:  # emulate negative indexing\n        return ll[len(ll) + index]\n    return default","typeGuard":null,"tryCatchPattern":"try:\n    node = ll[index]\nexcept ValueError:  # NOT IndexError — this class uses ValueError\n    node = None","preventionTips":["Never rely on negative indices with this class.","Catch ValueError, not IndexError, for subscripts.","Bounds-check with len() before every index expression."],"tags":["linked-list","index-error","value-error-quirk","subscript"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}