TheAlgorithms/Python · error · Exception

invalid operand!

Error message

invalid operand!

What it means

Raised by Vector.mul (and thus the * operator / __mul__) in linear_algebra/src/lib.py:127 when the right operand is neither a scalar (int/float) nor an equal-length Vector. The method dispatches on type: scalar -> scalar multiplication, Vector of the same size -> dot product; everything else (strings, lists, NumPy arrays, mismatched-size Vectors) falls into the error case.

Source

Thrown at linear_algebra/src/lib.py:127

    def __mul__(self, other: float) -> Vector: ...

    @overload
    def __mul__(self, other: Vector) -> float: ...

    def __mul__(self, other: float | Vector) -> float | Vector:
        """
        mul implements the scalar multiplication
        and the dot-product
        """
        if isinstance(other, (float, int)):
            ans = [c * other for c in self.__components]
            return Vector(ans)
        elif isinstance(other, Vector) and len(self) == len(other):
            size = len(self)
            prods = [self.__components[i] * other.component(i) for i in range(size)]
            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:

View on GitHub (pinned to f5988cc097)

Solutions

  1. Convert the operand before multiplying: use float(x) for scalars, Vector(list(arr)) for sequences/ndarrays.
  2. Check isinstance(other, (int, float)) or isinstance(other, Vector) and len(other) == len(self) first.
  3. Prefer calling the library's own dot usage pattern — keep both sides as Vector instances.
  4. Catch Exception around the multiplication when operand types come from untrusted input.

Example fix

// before
v = Vector([1, 2])
dot = v * np.array([3, 4])  # Exception: invalid operand!

// after
dot = v * Vector(list(np.array([3, 4])))  # or: sum(a*b for a, b in zip([1,2], [3,4]))
Defensive patterns

Strategy: type-guard

Validate before calling

from linear_algebra.src.lib import Vector

def coerce_operand(v: Vector, other):
    """Return an operand Vector.mul accepts, or None."""
    if isinstance(other, (int, float)):
        return other                      # scalar multiplication
    if isinstance(other, Vector) and len(other) == len(v):
        return other                      # dot product
    if hasattr(other, "__iter__") and len(list(other)) == len(v):
        return Vector(list(other))        # list / ndarray -> Vector
    return None

op = coerce_operand(v, candidate)
if op is None:
    raise TypeError(f"cannot multiply Vector by {type(candidate).__name__}")

Type guard

from linear_algebra.src.lib import Vector

def is_valid_mul_operand(other, expected_len: int) -> bool:
    return isinstance(other, (int, float)) or (
        isinstance(other, Vector) and len(other) == expected_len
    )

Try / catch

try:
    result = v * operand
except Exception as e:
    if "invalid operand" in str(e):
        raise TypeError(f"Vector * {type(operand).__name__} is not supported") from e
    raise

Prevention

When it happens

Trigger: Vector([1, 2]) * [1, 2] (list operand), Vector([1, 2]) * np.array([1, 2]) (ndarray is not int/float/Vector), Vector([1, 2]) * Vector([1, 2, 3]) (size mismatch on the dot-product path), or Vector([1, 2]) * "3" (numeric string).

Common situations: Mixing this library with NumPy code — ndarray operands are the classic trap since they look numeric. Also string numbers from JSON/CSV input that were never converted, or np.float64 usually works (it subclasses float) but other duck-typed numerics do not.

Related errors


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