TheAlgorithms/Python · error · ValueError

Matrix is not invertible

Error message

Matrix is not invertible

What it means

Raised by invert_matrix() in linear_algebra/matrix_inversion.py:26. The function calls np.linalg.inv() and translates NumPy's np.linalg.LinAlgError into a plain ValueError with the message 'Matrix is not invertible'. NumPy raises that LinAlgError when the input matrix is exactly singular (determinant 0), so no inverse exists.

Source

Thrown at linear_algebra/matrix_inversion.py:26

    Parameters:
    matrix (list[list[float]]): A square matrix.

    Returns:
    list[list[float]]: Inverted matrix if invertible, else raises error.

    >>> invert_matrix([[4.0, 7.0], [2.0, 6.0]])
    [[0.6000000000000001, -0.7000000000000001], [-0.2, 0.4]]
    >>> invert_matrix([[1.0, 2.0], [0.0, 0.0]])
    Traceback (most recent call last):
        ...
    ValueError: Matrix is not invertible
    """
    np_matrix = np.array(matrix)

    try:
        inv_matrix = np.linalg.inv(np_matrix)
    except np.linalg.LinAlgError:
        raise ValueError("Matrix is not invertible")

    return inv_matrix.tolist()


if __name__ == "__main__":
    mat = [[4.0, 7.0], [2.0, 6.0]]
    print("Original Matrix:")
    print(mat)
    print("Inverted Matrix:")
    print(invert_matrix(mat))

View on GitHub (pinned to f5988cc097)

Solutions

  1. Check the matrix condition/determinant before calling: np.linalg.cond(matrix) — if it is very large (e.g. > 1e12), treat the matrix as (numerically) singular.
  2. If a pseudo-inverse is acceptable, use np.linalg.pinv(matrix) which never raises for singular input.
  3. Remove or fix linearly dependent rows/columns in the source data so the matrix has full rank.
  4. Catch ValueError at the call site to handle degenerate input explicitly.

Example fix

// before
inv = invert_matrix([[1.0, 2.0], [2.0, 4.0]])  # ValueError

// after
import numpy as np
if np.linalg.cond(np.array(mat)) < 1e12:
    inv = invert_matrix(mat)
else:
    inv = np.linalg.pinv(np.array(mat)).tolist()  # least-squares fallback
Defensive patterns

Strategy: try-catch

Validate before calling

import numpy as np

def is_invertible(mat: list[list[float]], tol: float = 1e12) -> bool:
    a = np.asarray(mat, dtype=float)
    return a.ndim == 2 and a.shape[0] == a.shape[1] and np.linalg.cond(a) < tol

Type guard

def is_square_float_matrix(x) -> bool:
    return (
        isinstance(x, (list, tuple))
        and len(x) > 0
        and all(isinstance(r, (list, tuple)) and len(r) == len(x) for r in x)
    )

Try / catch

try:
    inv = invert_matrix(mat)
except ValueError:
    inv = np.linalg.pinv(np.asarray(mat, dtype=float)).tolist()  # least-squares fallback

Prevention

When it happens

Trigger: Calling invert_matrix([[1.0, 2.0], [0.0, 0.0]]) or any square matrix with linearly dependent rows/columns (determinant 0), e.g. [[1,2],[2,4]]. It is only raised for exact singularity; near-singular matrices return huge, numerically garbage values instead of raising.

Common situations: Feeding user-supplied or measured data whose rows are linearly dependent (duplicate rows, a column that is a multiple of another), constructing covariance/normal matrices from fewer samples than features (rank deficient), or unit tests that pass degenerate fixtures.

Related errors


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