{"record":{"id":"86b8625cddf4ccf6","repo":"TheAlgorithms/Python","slug":"list-index-out-of-range-86b862","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/doubly_linked_list.py","lineNumber":87,"sourceCode":"        >>> linked_list.insert_at_nth(1, 666)\n        Traceback (most recent call last):\n            ....\n        IndexError: list index out of range\n        >>> linked_list.insert_at_nth(0, 2)\n        >>> linked_list.insert_at_nth(0, 1)\n        >>> linked_list.insert_at_nth(2, 4)\n        >>> linked_list.insert_at_nth(2, 3)\n        >>> str(linked_list)\n        '1->2->3->4'\n        >>> linked_list.insert_at_nth(5, 5)\n        Traceback (most recent call last):\n            ....\n        IndexError: list index out of range\n        \"\"\"\n        length = len(self)\n\n        if not 0 <= index <= length:\n            raise IndexError(\"list index out of range\")\n        new_node = Node(data)\n        if self.head is None:\n            self.head = self.tail = new_node\n        elif index == 0:\n            self.head.previous = new_node\n            new_node.next = self.head\n            self.head = new_node\n        elif index == length:\n            self.tail.next = new_node\n            new_node.previous = self.tail\n            self.tail = new_node\n        else:\n            temp = self.head\n            for _ in range(index):\n                temp = temp.next\n            temp.previous.next = new_node\n            new_node.previous = temp.previous\n            new_node.next = temp","sourceCodeStart":69,"sourceCodeEnd":105,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/linked_list/doubly_linked_list.py#L69-L105","documentation":"DoublyLinkedList.insert_at_nth raises IndexError('list index out of range') when index is outside [0, len(list)] — note that index == len (append position) IS allowed, only values beyond it or negative values fail. Validation happens before any node rewiring, so a failed call leaves the list untouched.","triggerScenarios":"insert_at_nth(5, x) on a list of length 4 (only 0..4 valid); insert_at_nth(-1, x); computing the insertion point from a 1-based position without subtracting 1.","commonSituations":"Inserting at 'position n' where the caller counts positions 1..n+1; inserting after finding an element that is absent and using the search-loop counter as the index; race-free re-validation when the list shrank between length computation and insertion.","solutions":["Clamp or validate: use 0 <= index <= len(linked_list) before calling.","For append semantics call insert_at_nth(len(linked_list), data) or use the dedicated tail-insert API.","Convert 1-based user positions with index = position - 1 and re-check bounds."],"exampleFix":"# before\nlinked_list.insert_at_nth(len(linked_list) + 1, 5)  # IndexError\n# after\nlinked_list.insert_at_nth(len(linked_list), 5)  # append is legal","handlingStrategy":"validation","validationCode":"def safe_insert_nth(dll, index, data):\n    if 0 <= index <= len(dll):\n        dll.insert_at_nth(index, data)\n        return True\n    return False","typeGuard":null,"tryCatchPattern":"try:\n    dll.insert_at_nth(i, data)\nexcept IndexError:\n    # choose fallback: append at tail\n    dll.insert_at_nth(len(dll), data)","preventionTips":["Remember the inclusive bound: index == len is a valid append.","Convert 1-based positions to 0-based before inserting.","Use insert_at_tail-style calls (index == len) instead of computing near-bound indices."],"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"}