TheAlgorithms/Python · error · IndexError
list index out of range
Error message
list index out of range
What it means
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.
Source
Thrown at data_structures/linked_list/singly_linked_list.py:209
def insert_nth(self, index: int, data: Any) -> None:
"""
Insert data at given index.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")
>>> linked_list.insert_tail("second")
>>> linked_list.insert_tail("third")
>>> linked_list
first -> second -> third
>>> linked_list.insert_nth(1, "fourth")
>>> linked_list
first -> fourth -> second -> third
>>> linked_list.insert_nth(3, "fifth")
>>> linked_list
first -> fourth -> second -> fifth -> third
"""
if not 0 <= index <= len(self):
raise IndexError("list index out of range")
new_node = Node(data)
if self.head is None:
self.head = new_node
elif index == 0:
new_node.next_node = self.head # link new_node to head
self.head = new_node
else:
temp = self.head
for _ in range(index - 1):
temp = temp.next_node
new_node.next_node = temp.next_node
temp.next_node = new_node
def print_list(self) -> None: # print every node data
"""
This method prints every node data.
>>> linked_list = LinkedList()
>>> linked_list.insert_tail("first")View on GitHub (pinned to f5988cc097)
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.
Example fix
# before linked_list.insert_nth(len(linked_list) + 1, 'x') # IndexError # after linked_list.insert_nth(len(linked_list), 'x') # legal append
Defensive patterns
Strategy: validation
Validate before calling
def safe_insert_nth(ll, index, data):
if 0 <= index <= len(ll):
ll.insert_nth(index, data)
return True
return False Try / catch
try:
ll.insert_nth(i, data)
except IndexError:
ll.insert_tail(data) # fallback: append Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- list index out of range
- list index out of range.
- List index out of range.
- Position must be non-negative
- Out of bounds
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/6d497f6dea8dccda.
Report an issue: GitHub.