TheAlgorithms/Python · error · ValueError

Position must be non-negative

Error message

Position must be non-negative

What it means

Raised by LinkedList.add(item, position) (data_structures/linked_list/__init__.py) when position < 0. Positions are 0-indexed insertion slots; negative indices are not supported (unlike Python lists), so the method raises ValueError('Position must be non-negative') before walking the list. The sibling guard at the same call site raises 'Out of bounds' when the walk runs past the tail.

Source

Thrown at data_structures/linked_list/__init__.py:62

        3 --> 2 --> 4 --> 1

        # Test adding to a negative position
        >>> linked_list.add(5, -3)
        Traceback (most recent call last):
            ...
        ValueError: Position must be non-negative

        # Test adding to an out-of-bounds position
        >>> linked_list.add(5,7)
        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

View on GitHub (pinned to f5988cc097)

Solutions

  1. Validate/clamp the index at the caller: `pos = max(0, pos)` or reject negatives with your own message
  2. Fix index math — compute positions forward from the head, not as negative offsets from the tail
  3. If you need end-insertion, use the size: add(item, linked_list.size) appends at the tail

Example fix

# before
linked_list.add(5, -1)  # ValueError

# after
linked_list.add(5, linked_list.size)  # append at end
Defensive patterns

Strategy: validation

Validate before calling

position = max(0, position)
linked_list.add(item, position)

Type guard

def is_valid_position(pos: object, size: int) -> bool:
    return isinstance(pos, int) and 0 <= pos <= size

Try / catch

try:
    linked_list.add(item, position)
except ValueError as e:
    if 'non-negative' not in str(e):
        raise
    linked_list.add(item, 0)  # fall back to head insert

Prevention

When it happens

Trigger: linked_list.add(item, -1) attempting list-style negative indexing; position computed as `i - len(...)` which goes negative at i == 0; user-supplied index parsed without validation.

Common situations: Porting list code that uses [-1] semantics; index arithmetic that assumes a non-empty list; CLI/form input for a position not validated as >= 0.

Related errors


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