{"record":{"id":"0dda308324bd83d3","repo":"TheAlgorithms/Python","slug":"list-index-out-of-range-0dda30","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/circular_linked_list.py","lineNumber":69,"sourceCode":"\n    def insert_head(self, data: Any) -> None:\n        \"\"\"\n        Insert a node with the given data at the beginning of the Circular Linked List.\n        \"\"\"\n        self.insert_nth(0, data)\n\n    def insert_nth(self, index: int, data: Any) -> None:\n        \"\"\"\n        Insert the data of the node at the nth pos in the Circular Linked List.\n        Args:\n            index: The index at which the data should be inserted.\n            data: The data to be inserted.\n\n        Raises:\n            IndexError: If the index is out of range.\n        \"\"\"\n        if index < 0 or index > len(self):\n            raise IndexError(\"list index out of range.\")\n        new_node: Node = Node(data)\n        if self.head is None:\n            new_node.next_node = new_node  # First node points to itself\n            self.tail = self.head = new_node\n        elif index == 0:  # Insert at the head\n            new_node.next_node = self.head\n            assert self.tail is not None  # List is not empty, tail exists\n            self.head = self.tail.next_node = new_node\n        else:\n            temp: Node | None = self.head\n            for _ in range(index - 1):\n                assert temp is not None\n                temp = temp.next_node\n            assert temp is not None\n            new_node.next_node = temp.next_node\n            temp.next_node = new_node\n            if index == len(self) - 1:  # Insert at the tail\n                self.tail = new_node","sourceCodeStart":51,"sourceCodeEnd":87,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/linked_list/circular_linked_list.py#L51-L87","documentation":"Raised by CircularLinkedList.insert_nth(index, data) when index < 0 or index > len(self) — the valid insertion window is 0..length inclusive (index == length appends). It raises IndexError (not ValueError) with message 'list index out of range.', deliberately mirroring CPython list.insert-adjacent error semantics. Because the list is circular, insertion at 0 relinks tail.next_node rather than a head pointer alone.","triggerScenarios":"cll.insert_nth(-1, x); cll.insert_nth(len(cll) + 1, x) on a list of known length; insert_nth called on a list whose length shrank after prior deletions while the caller cached the old length.","commonSituations":"Index math derived from enumerate offsets that go negative; UI-driven insert-at-position with 1-based input passed through unconverted; cached length going stale.","solutions":["Validate before calling: `if 0 <= index <= len(cll): cll.insert_nth(index, data)`","Convert 1-based user input: index = user_pos - 1, then bounds-check","Recompute len(cll) at call time instead of caching it"],"exampleFix":"# before\ncll.insert_nth(len(cll) + 5, 'x')  # IndexError\n\n# after\nindex = min(index, len(cll))\nindex = max(index, 0)\ncll.insert_nth(index, 'x')","handlingStrategy":"validation","validationCode":"if not 0 <= index <= len(cll):\n    raise IndexError(f'index {index} outside 0..{len(cll)}')\ncll.insert_nth(index, data)","typeGuard":"def is_valid_nth(cll, index: object) -> bool:\n    return isinstance(index, int) and 0 <= index <= len(cll)","tryCatchPattern":"try:\n    cll.insert_nth(index, data)\nexcept IndexError:\n    cll.insert_nth(len(cll), data)  # append on out-of-range","preventionTips":["Bounds-check 0 <= index <= len(cll) before every insert_nth","Convert 1-based UI positions to 0-based before calling","Read len(cll) fresh — circular lists shrink on delete like any other"],"tags":["linked-list","circular-list","index-error","insert","out-of-bounds"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}