TheAlgorithms/Python · error · TypeError

A Matrix can only be multiplied by an int, float, or another

Error message

A Matrix can only be multiplied by an int, float, or another matrix

What it means

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.

Source

Thrown at matrix/matrix_class.py:336

    def __mul__(self, other: Matrix | float) -> Matrix:
        if isinstance(other, (int, float)):
            return Matrix(
                [[int(element * other) for element in row] for row in self.rows]
            )
        elif isinstance(other, Matrix):
            if self.num_columns != other.num_rows:
                raise ValueError(
                    "The number of columns in the first matrix must "
                    "be equal to the number of rows in the second"
                )
            return Matrix(
                [
                    [Matrix.dot_product(row, column) for column in other.columns()]
                    for row in self.rows
                ]
            )
        else:
            raise TypeError(
                "A Matrix can only be multiplied by an int, float, or another matrix"
            )

    def __pow__(self, other: int) -> Matrix:
        if not isinstance(other, int):
            raise TypeError("A Matrix can only be raised to the power of an int")
        if not self.is_square:
            raise ValueError("Only square matrices can be raised to a power")
        if other == 0:
            return self.identity()
        if other < 0:
            if self.is_invertable():
                return self.inverse() ** (-other)
            raise ValueError(
                "Only invertable matrices can be raised to a negative power"
            )
        result = self
        for _ in range(other - 1):

View on GitHub (pinned to f5988cc097)

Solutions

  1. Wrap raw nested lists in the Matrix class first: matrix * Matrix([[1, 2], [3, 4]]).
  2. Convert array-likes from other libraries to plain scalars or a Matrix before multiplying (e.g. float(np_value) for scalars).
  3. 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 *.
  4. Check for accidental string operands coming from file/config parsing with isinstance checks before the multiplication.

Example fix

# before
result = m * [[1, 0], [0, 1]]  # TypeError

# after
result = m * Matrix([[1, 0], [0, 1]])
Defensive patterns

Strategy: type-guard

Validate before calling

from matrix_class import Matrix

if not isinstance(other, (Matrix, int, float)):
    if isinstance(other, (list, tuple)):
        other = Matrix(other)  # wrap raw nested lists
    else:
        raise TypeError(f"cannot multiply Matrix by {type(other).__name__}")
result = matrix * other

Type guard

def is_scalar_or_matrix(x) -> bool:
    """Guard for Matrix.__mul__ operands: int/float scalar or Matrix."""
    return isinstance(x, (Matrix, int, float))

Try / catch

try:
    result = matrix * operand
except TypeError as e:
    if "int, float, or another matrix" in str(e):
        operand = Matrix(operand) if isinstance(operand, list) else float(operand)
        result = matrix * operand
    else:
        raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


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