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
- 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.
- If a pseudo-inverse is acceptable, use np.linalg.pinv(matrix) which never raises for singular input.
- Remove or fix linearly dependent rows/columns in the source data so the matrix has full rank.
- 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
- Check np.linalg.cond(matrix) before inverting; cond > ~1e12 means the result would be numerically meaningless even if it does not raise.
- Validate input is a square nested list of numbers before calling.
- For rank-deficient data (fewer samples than features, collinear columns), use np.linalg.pinv by design instead of catching after the fact.
- Remember this only catches exact singularity — near-singular matrices silently return huge values, so a condition check is the real guard.
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
- Coefficient matrix dimensions must be nxn but received {rows
- Constant matrix must be nx1 but received {rows2}x{cols2}
- Coefficient and constant matrices dimensions must be nxn and
- Number of initial values must be equal to number of rows in
- 'table' has to be of square shaped array but got a {rows}x{c
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/14ee96dc1f05dd47.
Report an issue: GitHub.