TheAlgorithms/Python · error · ValueError

Out of bounds

Error message

Out of bounds

What it means

Raised by LinkedList.add(item, position) when the traversal `for _ in range(position - 1)` walks current to None before reaching the target slot — i.e. position exceeds the list length (strictly: position > size, since position == size appends). The node chain ended, so there is no node to attach after; ValueError('Out of bounds') fires. Note position == 0 and empty-list cases are handled earlier by the head-insert branch.

Source

Thrown at data_structures/linked_list/__init__.py:72

        Traceback (most recent call last):
            ...
        ValueError: Out of bounds
        >>> linked_list.add(5, 4)
        >>> print(linked_list)
        3 --> 2 --> 4 --> 1 --> 5
        """
        if position < 0:
            raise ValueError("Position must be non-negative")

        if position == 0 or self.head is None:
            new_node = Node(item, self.head)
            self.head = new_node
        else:
            current = self.head
            for _ in range(position - 1):
                current = current.next
                if current is None:
                    raise ValueError("Out of bounds")
            new_node = Node(item, current.next)
            current.next = new_node
        self.size += 1

    def remove(self) -> Any:
        # Switched 'self.is_empty()' to 'self.head is None'
        # because mypy was considering the possibility that 'self.head'
        # can be None in below else part and giving error
        if self.head is None:
            return None
        else:
            item = self.head.item
            self.head = self.head.next
            self.size -= 1
            return item

    def is_empty(self) -> bool:
        return self.head is None

View on GitHub (pinned to f5988cc097)

Solutions

  1. Clamp to append: `pos = min(pos, linked_list.size)` before calling
  2. Re-check size immediately before the insert if the list may have changed
  3. For pure append, call add(item, linked_list.size)

Example fix

# before
linked_list.add(5, 7)  # list has 4 nodes -> ValueError

# after
linked_list.add(5, min(7, linked_list.size))  # appends
Defensive patterns

Strategy: validation

Validate before calling

position = min(position, linked_list.size)
linked_list.add(item, position)

Try / catch

try:
    linked_list.add(item, position)
except ValueError as e:
    if 'Out of bounds' not in str(e):
        raise
    linked_list.add(item, linked_list.size)  # append instead

Prevention

When it happens

Trigger: add(5, 7) on a 4-element list (the doctest example); using position == size + 1 or more; computing position from a stale size after removals shrank the list.

Common situations: Insert-at-index code ported from lists where bounds drift; concurrent modification (list shrank between size check and add); off-by-one in append logic (use size, not size + 1).

Related errors


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