{"record":{"id":"6d497f6dea8dccda","repo":"TheAlgorithms/Python","slug":"list-index-out-of-range-6d497f","errorCode":null,"errorMessage":"list index out of range","messagePattern":"list index out of range","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"data_structures/linked_list/singly_linked_list.py","lineNumber":209,"sourceCode":"\n    def insert_nth(self, index: int, data: Any) -> None:\n        \"\"\"\n        Insert data at given index.\n        >>> linked_list = LinkedList()\n        >>> linked_list.insert_tail(\"first\")\n        >>> linked_list.insert_tail(\"second\")\n        >>> linked_list.insert_tail(\"third\")\n        >>> linked_list\n        first -> second -> third\n        >>> linked_list.insert_nth(1, \"fourth\")\n        >>> linked_list\n        first -> fourth -> second -> third\n        >>> linked_list.insert_nth(3, \"fifth\")\n        >>> linked_list\n        first -> fourth -> second -> fifth -> third\n        \"\"\"\n        if not 0 <= index <= len(self):\n            raise IndexError(\"list index out of range\")\n        new_node = Node(data)\n        if self.head is None:\n            self.head = new_node\n        elif index == 0:\n            new_node.next_node = self.head  # link new_node to head\n            self.head = new_node\n        else:\n            temp = self.head\n            for _ in range(index - 1):\n                temp = temp.next_node\n            new_node.next_node = temp.next_node\n            temp.next_node = new_node\n\n    def print_list(self) -> None:  # print every node data\n        \"\"\"\n        This method prints every node data.\n        >>> linked_list = LinkedList()\n        >>> linked_list.insert_tail(\"first\")","sourceCodeStart":191,"sourceCodeEnd":227,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/linked_list/singly_linked_list.py#L191-L227","documentation":"LinkedList.insert_nth raises IndexError('list index out of range') when index is outside [0, len]. Index == len is the legal append position; negative indices always fail. This is the IndexError counterpart to the ValueError used by __getitem__/__setitem__ in the same file — the class mixes exception types by operation.","triggerScenarios":"insert_nth(5, x) on a 4-node list; insert_nth(-1, x); index arithmetic off by one when inserting before/after a located node.","commonSituations":"Insertion loops with range(len(linked_list)+2); mixing up the inclusive/exclusive bounds between insert (<= len) and delete (< len); 1-based positions not converted.","solutions":["Validate 0 <= index <= len(linked_list) before calling.","Prefer insert_tail()/insert_head() for the two common ends rather than computing indices.","Catch IndexError for insert failures, ValueError for get/set failures — do not share one handler blindly."],"exampleFix":"# before\nlinked_list.insert_nth(len(linked_list) + 1, 'x')  # IndexError\n# after\nlinked_list.insert_nth(len(linked_list), 'x')  # legal append","handlingStrategy":"validation","validationCode":"def safe_insert_nth(ll, index, data):\n    if 0 <= index <= len(ll):\n        ll.insert_nth(index, data)\n        return True\n    return False","typeGuard":null,"tryCatchPattern":"try:\n    ll.insert_nth(i, data)\nexcept IndexError:\n    ll.insert_tail(data)  # fallback: append","preventionTips":["Insert bound is inclusive (<= len); delete bound is exclusive (< len).","Use insert_head/insert_tail for the ends instead of index math.","Catch IndexError for insert_nth, ValueError for get/set — the types differ."],"tags":["linked-list","index-error","insert","bounds-check"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}