TheAlgorithms/Python · error · IndexError
list index out of range
Error message
list index out of range
What it means
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.
Source
Thrown at data_structures/linked_list/doubly_linked_list.py:87
>>> linked_list.insert_at_nth(1, 666)
Traceback (most recent call last):
....
IndexError: list index out of range
>>> linked_list.insert_at_nth(0, 2)
>>> linked_list.insert_at_nth(0, 1)
>>> linked_list.insert_at_nth(2, 4)
>>> linked_list.insert_at_nth(2, 3)
>>> str(linked_list)
'1->2->3->4'
>>> linked_list.insert_at_nth(5, 5)
Traceback (most recent call last):
....
IndexError: list index out of range
"""
length = len(self)
if not 0 <= index <= length:
raise IndexError("list index out of range")
new_node = Node(data)
if self.head is None:
self.head = self.tail = new_node
elif index == 0:
self.head.previous = new_node
new_node.next = self.head
self.head = new_node
elif index == length:
self.tail.next = new_node
new_node.previous = self.tail
self.tail = new_node
else:
temp = self.head
for _ in range(index):
temp = temp.next
temp.previous.next = new_node
new_node.previous = temp.previous
new_node.next = tempView on GitHub (pinned to f5988cc097)
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.
Example fix
# before linked_list.insert_at_nth(len(linked_list) + 1, 5) # IndexError # after linked_list.insert_at_nth(len(linked_list), 5) # append is legal
Defensive patterns
Strategy: validation
Validate before calling
def safe_insert_nth(dll, index, data):
if 0 <= index <= len(dll):
dll.insert_at_nth(index, data)
return True
return False Try / catch
try:
dll.insert_at_nth(i, data)
except IndexError:
# choose fallback: append at tail
dll.insert_at_nth(len(dll), data) Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
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/86b8625cddf4ccf6.
Report an issue: GitHub.