TheAlgorithms/Python · error · ValueError

list index out of range.

Error message

list index out of range.

What it means

LinkedList.__getitem__ raises ValueError('list index out of range.') for index outside [0, len). Note the type is ValueError, not the IndexError CPython lists raise — a deliberate quirk of this class; match on the class's behavior, not the builtin's.

Source

Thrown at data_structures/linked_list/singly_linked_list.py:126

    def __getitem__(self, index: int) -> Any:
        """
        Indexing Support. Used to get a node at particular position
        >>> linked_list = LinkedList()
        >>> for i in range(0, 10):
        ...     linked_list.insert_nth(i, i)
        >>> all(str(linked_list[i]) == str(i) for i in range(0, 10))
        True
        >>> linked_list[-10]
        Traceback (most recent call last):
            ...
        ValueError: list index out of range.
        >>> linked_list[len(linked_list)]
        Traceback (most recent call last):
            ...
        ValueError: list index out of range.
        """
        if not 0 <= index < len(self):
            raise ValueError("list index out of range.")
        for i, node in enumerate(self):
            if i == index:
                return node
        return None

    # Used to change the data of a particular node
    def __setitem__(self, index: int, data: Any) -> None:
        """
        >>> linked_list = LinkedList()
        >>> for i in range(0, 10):
        ...     linked_list.insert_nth(i, i)
        >>> linked_list[0] = 666
        >>> linked_list[0]
        666
        >>> linked_list[5] = -666
        >>> linked_list[5]
        -666
        >>> linked_list[-10] = 666

View on GitHub (pinned to f5988cc097)

Solutions

  1. Validate 0 <= index < len(linked_list) before subscripting.
  2. Emulate negative indices yourself: index = index if index >= 0 else len(linked_list) + index, then bounds-check.
  3. In callers, catch ValueError for this class's subscripts, not IndexError.

Example fix

# before
last = linked_list[-1]  # ValueError: list index out of range.
# after
last = linked_list[len(linked_list) - 1] if len(linked_list) else None
Defensive patterns

Strategy: validation

Validate before calling

def get(ll, index, default=None):
    if 0 <= index < len(ll):
        return ll[index]
    if -len(ll) <= index < 0:  # emulate negative indexing
        return ll[len(ll) + index]
    return default

Try / catch

try:
    node = ll[index]
except ValueError:  # NOT IndexError — this class uses ValueError
    node = None

Prevention

When it happens

Trigger: linked_list[-1] (negative indices are NOT supported), linked_list[len(linked_list)], or any index on an empty list.

Common situations: Porting list/tuple indexing code that relies on negative indices; loops using range(len+1) off by one; catching IndexError in caller code and having this ValueError slip through.

Related errors


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