{"record":{"id":"559b1e3217700aba","repo":"TheAlgorithms/Python","slug":"invalid-operand","errorCode":null,"errorMessage":"invalid operand!","messagePattern":"invalid operand!","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"linear_algebra/src/lib.py","lineNumber":127,"sourceCode":"    def __mul__(self, other: float) -> Vector: ...\n\n    @overload\n    def __mul__(self, other: Vector) -> float: ...\n\n    def __mul__(self, other: float | Vector) -> float | Vector:\n        \"\"\"\n        mul implements the scalar multiplication\n        and the dot-product\n        \"\"\"\n        if isinstance(other, (float, int)):\n            ans = [c * other for c in self.__components]\n            return Vector(ans)\n        elif isinstance(other, Vector) and len(self) == len(other):\n            size = len(self)\n            prods = [self.__components[i] * other.component(i) for i in range(size)]\n            return sum(prods)\n        else:  # error case\n            raise Exception(\"invalid operand!\")\n\n    def copy(self) -> Vector:\n        \"\"\"\n        copies this vector and returns it.\n        \"\"\"\n        return Vector(self.__components)\n\n    def component(self, i: int) -> float:\n        \"\"\"\n        input: index (0-indexed)\n        output: the i-th component of the vector.\n        \"\"\"\n        if isinstance(i, int) and -len(self.__components) <= i < len(self.__components):\n            return self.__components[i]\n        else:\n            raise Exception(\"index out of range\")\n\n    def change_component(self, pos: int, value: float) -> None:","sourceCodeStart":109,"sourceCodeEnd":145,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/linear_algebra/src/lib.py#L109-L145","documentation":"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.","triggerScenarios":"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).","commonSituations":"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.","solutions":["Convert the operand before multiplying: use float(x) for scalars, Vector(list(arr)) for sequences/ndarrays.","Check isinstance(other, (int, float)) or isinstance(other, Vector) and len(other) == len(self) first.","Prefer calling the library's own dot usage pattern — keep both sides as Vector instances.","Catch Exception around the multiplication when operand types come from untrusted input."],"exampleFix":"// before\nv = Vector([1, 2])\ndot = v * np.array([3, 4])  # Exception: invalid operand!\n\n// after\ndot = v * Vector(list(np.array([3, 4])))  # or: sum(a*b for a, b in zip([1,2], [3,4]))","handlingStrategy":"type-guard","validationCode":"from linear_algebra.src.lib import Vector\n\ndef coerce_operand(v: Vector, other):\n    \"\"\"Return an operand Vector.mul accepts, or None.\"\"\"\n    if isinstance(other, (int, float)):\n        return other                      # scalar multiplication\n    if isinstance(other, Vector) and len(other) == len(v):\n        return other                      # dot product\n    if hasattr(other, \"__iter__\") and len(list(other)) == len(v):\n        return Vector(list(other))        # list / ndarray -> Vector\n    return None\n\nop = coerce_operand(v, candidate)\nif op is None:\n    raise TypeError(f\"cannot multiply Vector by {type(candidate).__name__}\")","typeGuard":"from linear_algebra.src.lib import Vector\n\ndef is_valid_mul_operand(other, expected_len: int) -> bool:\n    return isinstance(other, (int, float)) or (\n        isinstance(other, Vector) and len(other) == expected_len\n    )","tryCatchPattern":"try:\n    result = v * operand\nexcept Exception as e:\n    if \"invalid operand\" in str(e):\n        raise TypeError(f\"Vector * {type(operand).__name__} is not supported\") from e\n    raise","preventionTips":["Never pass raw NumPy arrays, lists, or numeric strings to Vector * — convert with Vector(list(x)) or float(x) first.","Remember the size rule: dot products need an equal-length Vector; keep both operands as this library's Vector type.","The overload only accepts int/float scalars — duck-typed numerics that are not int/float subclasses will fail; coerce explicitly.","Wrap multiplication of externally-typed values in a coercion helper so the check lives in one place."],"tags":["linear-algebra","vector","type-error","dot-product","type-guard"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}