{"record":{"id":"1583f6b6696bb0f4","repo":"TheAlgorithms/Python","slug":"a-matrix-can-only-be-multiplied-by-an-int-float","errorCode":null,"errorMessage":"A Matrix can only be multiplied by an int, float, or another matrix","messagePattern":"A Matrix can only be multiplied by an int, float, or another matrix","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"matrix/matrix_class.py","lineNumber":336,"sourceCode":"    def __mul__(self, other: Matrix | float) -> Matrix:\n        if isinstance(other, (int, float)):\n            return Matrix(\n                [[int(element * other) for element in row] for row in self.rows]\n            )\n        elif isinstance(other, Matrix):\n            if self.num_columns != other.num_rows:\n                raise ValueError(\n                    \"The number of columns in the first matrix must \"\n                    \"be equal to the number of rows in the second\"\n                )\n            return Matrix(\n                [\n                    [Matrix.dot_product(row, column) for column in other.columns()]\n                    for row in self.rows\n                ]\n            )\n        else:\n            raise TypeError(\n                \"A Matrix can only be multiplied by an int, float, or another matrix\"\n            )\n\n    def __pow__(self, other: int) -> Matrix:\n        if not isinstance(other, int):\n            raise TypeError(\"A Matrix can only be raised to the power of an int\")\n        if not self.is_square:\n            raise ValueError(\"Only square matrices can be raised to a power\")\n        if other == 0:\n            return self.identity()\n        if other < 0:\n            if self.is_invertable():\n                return self.inverse() ** (-other)\n            raise ValueError(\n                \"Only invertable matrices can be raised to a negative power\"\n            )\n        result = self\n        for _ in range(other - 1):","sourceCodeStart":318,"sourceCodeEnd":354,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/matrix/matrix_class.py#L318-L354","documentation":"Raised by Matrix.__mul__ when the right operand is neither an int/float (scalar multiplication) nor a Matrix instance. The operator explicitly rejects all other types instead of returning NotImplemented, so any unsupported operand surfaces immediately as a TypeError. Typical victims include strings, complex numbers, lists of lists (raw data not wrapped in Matrix), and duck-typed matrix objects from other libraries.","triggerScenarios":"matrix * [[1, 2], [3, 4]] (raw nested list instead of a Matrix), matrix * (2 + 3j) (complex scalar), matrix * \"3\" (numeric string), or matrix * some_numpy_array. Also triggered by objects that subclass neither Matrix nor float/int.","commonSituations":"Mixing this Matrix class with NumPy arrays or Pandas DataFrames in the same expression; reading matrix data from JSON/CSV as nested lists and multiplying without conversion; assuming Python duck typing will accept any array-like object.","solutions":["Wrap raw nested lists in the Matrix class first: matrix * Matrix([[1, 2], [3, 4]]).","Convert array-likes from other libraries to plain scalars or a Matrix before multiplying (e.g. float(np_value) for scalars).","If you need interop with NumPy semantics, convert the Matrix to a list of rows and use NumPy's @ operator instead of this class's *.","Check for accidental string operands coming from file/config parsing with isinstance checks before the multiplication."],"exampleFix":"# before\nresult = m * [[1, 0], [0, 1]]  # TypeError\n\n# after\nresult = m * Matrix([[1, 0], [0, 1]])","handlingStrategy":"type-guard","validationCode":"from matrix_class import Matrix\n\nif not isinstance(other, (Matrix, int, float)):\n    if isinstance(other, (list, tuple)):\n        other = Matrix(other)  # wrap raw nested lists\n    else:\n        raise TypeError(f\"cannot multiply Matrix by {type(other).__name__}\")\nresult = matrix * other","typeGuard":"def is_scalar_or_matrix(x) -> bool:\n    \"\"\"Guard for Matrix.__mul__ operands: int/float scalar or Matrix.\"\"\"\n    return isinstance(x, (Matrix, int, float))","tryCatchPattern":"try:\n    result = matrix * operand\nexcept TypeError as e:\n    if \"int, float, or another matrix\" in str(e):\n        operand = Matrix(operand) if isinstance(operand, list) else float(operand)\n        result = matrix * operand\n    else:\n        raise","preventionTips":["Normalize array-likes to this Matrix class at your data-ingestion boundary, not at each multiplication site.","Never assume duck typing: this operator accepts exactly int, float, and Matrix.","Add isinstance assertions in tests so unsupported types fail loudly at the test layer."],"tags":["matrix","typeerror","type-mismatch","operator-overloading"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}