TheAlgorithms/Python · error · IndexError

List index out of range.

Error message

List index out of range.

What it means

LinkedList.delete_nth raises IndexError('List index out of range.') — capital 'L' and trailing period — when index is outside [0, len-1]. Validation happens before any pointer rewiring so the list is unchanged on failure.

Source

Thrown at data_structures/linked_list/singly_linked_list.py:313

        >>> linked_list.insert_tail("second")
        >>> linked_list.insert_tail("third")
        >>> linked_list
        first -> second -> third
        >>> linked_list.delete_nth(1) # delete middle
        'second'
        >>> linked_list
        first -> third
        >>> linked_list.delete_nth(5) # this raises error
        Traceback (most recent call last):
            ...
        IndexError: List index out of range.
        >>> linked_list.delete_nth(-1) # this also raises error
        Traceback (most recent call last):
            ...
        IndexError: List index out of range.
        """
        if not 0 <= index <= len(self) - 1:  # test if index is valid
            raise IndexError("List index out of range.")
        delete_node = self.head  # default first node
        if index == 0:
            self.head = self.head.next_node
        else:
            temp = self.head
            for _ in range(index - 1):
                temp = temp.next_node
            delete_node = temp.next_node
            temp.next_node = temp.next_node.next_node
        return delete_node.data

    def is_empty(self) -> bool:
        """
        Check if linked list is empty.
        >>> linked_list = LinkedList()
        >>> linked_list.is_empty()
        True
        >>> linked_list.insert_head("first")

View on GitHub (pinned to f5988cc097)

Solutions

  1. Check 0 <= index <= len(linked_list) - 1 before deleting.
  2. In deletion loops, iterate 'while len(linked_list) > target:' or recompute length each pass.
  3. Match the exact message style ('List index...') if tests assert on it; catch IndexError otherwise.

Example fix

# before
linked_list.delete_nth(len(linked_list))  # IndexError
# after
n = len(linked_list)
if 0 <= idx <= n - 1:
    linked_list.delete_nth(idx)
Defensive patterns

Strategy: validation

Validate before calling

def safe_delete_nth(ll, index):
    if 0 <= index <= len(ll) - 1:
        return ll.delete_nth(index)
    return None

Try / catch

try:
    value = ll.delete_nth(i)
except IndexError:
    value = None

Prevention

When it happens

Trigger: delete_nth(len(linked_list)); delete_nth(-1) (both shown in the doctests); delete_nth(0) on an empty list.

Common situations: Reusing an insert bounds check (<= len) for delete; deleting in a loop with a cached stale length; parsers that pass user-entered 1-based positions unchecked.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/efd76c952e65c65d. Report an issue: GitHub.