TheAlgorithms/Python · error · Exception

index out of range

Error message

index out of range

What it means

Raised by Vector.component(i) in linear_algebra/src/lib.py:143 when the requested index falls outside the valid range [-len, len). The method deliberately validates i is an int within that range and raises a bare Exception 'index out of range' rather than letting the list raise IndexError — but note it also rejects non-int indices (e.g. floats or bool-handled edge cases) with the same message.

Source

Thrown at linear_algebra/src/lib.py:143

            return sum(prods)
        else:  # error case
            raise Exception("invalid operand!")

    def copy(self) -> Vector:
        """
        copies this vector and returns it.
        """
        return Vector(self.__components)

    def component(self, i: int) -> float:
        """
        input: index (0-indexed)
        output: the i-th component of the vector.
        """
        if isinstance(i, int) and -len(self.__components) <= i < len(self.__components):
            return self.__components[i]
        else:
            raise Exception("index out of range")

    def change_component(self, pos: int, value: float) -> None:
        """
        input: an index (pos) and a value
        changes the specified component (pos) with the
        'value'
        """
        # precondition
        assert -len(self.__components) <= pos < len(self.__components)
        self.__components[pos] = value

    def euclidean_length(self) -> float:
        """
        returns the euclidean length of the vector

        >>> Vector([2, 3, 4]).euclidean_length()
        5.385164807134504
        >>> Vector([1]).euclidean_length()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Clamp and int-cast the index: i = int(i); if not -len(v) <= i < len(v): raise ...
  2. Fix loop bounds to range(len(v)) — an inclusive end is the usual off-by-one.
  3. Remember negative indices are supported down to -len, but -len - 1 and beyond raise.
  4. Catch Exception narrowly if indices come from user input and you want graceful handling.

Example fix

// before
v = Vector([1, 2, 3])
val = v.component(3)  # Exception: index out of range

// after
i = min(max(int(i), -len(v)), len(v) - 1)
val = v.component(i)
Defensive patterns

Strategy: validation

Validate before calling

i = int(i)
n = len(v)
if not -n <= i < n:
    raise IndexError(f"index {i} out of range for size {n}")
value = v.component(i)

Type guard

def is_valid_vector_index(v, i) -> bool:
    return isinstance(i, int) and -len(v) <= i < len(v)

Try / catch

try:
    value = v.component(i)
except Exception as e:
    if "index out of range" in str(e):
        raise IndexError(f"component({i!r}) invalid for size {len(v)}") from e
    raise

Prevention

When it happens

Trigger: Calling v.component(5) on a 3-component vector, v.component(-4) (one past the negative end), or v.component(1.0) — a float index that would work with list indexing fails the isinstance(i, int) check.

Common situations: Off-by-one loop bounds (range(len(v) + 1)), index arithmetic that goes negative past the start, or indices computed from float math (i / 2) that were never coerced to int.

Related errors


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