TheAlgorithms/Python · error · TypeError

Only matrices with a non-zero determinant have an inverse

Error message

Only matrices with a non-zero determinant have an inverse

What it means

Error "Only matrices with a non-zero determinant have an inverse" thrown in TheAlgorithms/Python.

Source

Thrown at matrix/matrix_class.py:226

                    if (row + column) % 2 == 0
                    else self.minors().rows[row][column] * -1
                    for column in range(self.minors().num_columns)
                ]
                for row in range(self.minors().num_rows)
            ]
        )

    def adjugate(self) -> Matrix:
        values = [
            [self.cofactors().rows[column][row] for column in range(self.num_columns)]
            for row in range(self.num_rows)
        ]
        return Matrix(values)

    def inverse(self) -> Matrix:
        determinant = self.determinant()
        if not determinant:
            raise TypeError("Only matrices with a non-zero determinant have an inverse")
        return self.adjugate() * (1 / determinant)

    def __repr__(self) -> str:
        return str(self.rows)

    def __str__(self) -> str:
        if self.num_rows == 0:
            return "[]"
        if self.num_rows == 1:
            return "[[" + ". ".join(str(self.rows[0])) + "]]"
        return (
            "["
            + "\n ".join(
                [
                    "[" + ". ".join([str(value) for value in row]) + ".]"
                    for row in self.rows
                ]
            )

View on GitHub (pinned to f5988cc097)

Solutions

  1. Only invertible matrices (non-zero determinant) have an inverse; check the determinant first.

When it happens

Trigger: Thrown at matrix/matrix_class.py:226 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/9136fd141b237763. Report an issue: GitHub.