TheAlgorithms/Python · error · ValueError

Addition requires matrices of the same order

Error message

Addition requires matrices of the same order

What it means

Error "Addition requires matrices of the same order" thrown in TheAlgorithms/Python.

Source

Thrown at matrix/matrix_class.py:300

                [*self.rows[i][0:position], column[i], *self.rows[i][position:]]
                for i in range(self.num_rows)
            ]

    # MATRIX OPERATIONS
    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Matrix):
            return NotImplemented
        return self.rows == other.rows

    def __ne__(self, other: object) -> bool:
        return not self == other

    def __neg__(self) -> Matrix:
        return self * -1

    def __add__(self, other: Matrix) -> Matrix:
        if self.order != other.order:
            raise ValueError("Addition requires matrices of the same order")
        return Matrix(
            [
                [self.rows[i][j] + other.rows[i][j] for j in range(self.num_columns)]
                for i in range(self.num_rows)
            ]
        )

    def __sub__(self, other: Matrix) -> Matrix:
        if self.order != other.order:
            raise ValueError("Subtraction requires matrices of the same order")
        return Matrix(
            [
                [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)]
                for i in range(self.num_rows)
            ]
        )

    def __mul__(self, other: Matrix | float) -> Matrix:

View on GitHub (pinned to f5988cc097)

Solutions

  1. Add only matrices with identical dimensions.

When it happens

Trigger: Thrown at matrix/matrix_class.py:300 when the library encounters an invalid state.

Common situations: See trigger scenarios.


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