Matrix Inverse in Python with numpy.linalg.inv
Find the inverse of a square matrix with np.linalg.inv, check it against the identity, and learn when not to use it.
- np.linalg.inv and the identity matrix
- Why the determinant must not be 0
- Why np.linalg.solve beats inv(A) @ b
- [[0.6, -0.7]
- [-0.2, 0.4]]
- [[1, 0]
- [0, 1]]
- 10
- not 0, so A has an inverse
Undoing a matrix
The problem
Linear algebra courses, transformations and textbook formulas use the inverse matrix all the time. Inverting even a 3 x 3 matrix by hand is tedious, and it is easy to miss that a matrix has no inverse at all.
Think of it like this
A matrix inverse is like the undo button. If A transforms a shape, for example stretches and turns it, the inverse transforms it straight back, so doing A and then its inverse leaves everything unchanged.
A🔄 The transformation you applynp.linalg.inv(A)↩️ The undo buttonA @ A_inv🟰 Do it and undo it: nothing changesnp.linalg.det(A) == 0🚫 Some transformations cannot be undoneThe inverse of a square matrix A is the matrix A⁻¹ with A @ A⁻¹ = I, the identity matrix. It exists only when the determinant of A is not 0.
Key points
np.linalg.inv(A)returns the inverse as a new array.A @ A_invshould be the identitynp.eye(2); compare withnp.allclose.np.linalg.det(A)is 10 here; a determinant of 0 means no inverse.np.linalg.solve(A, b)gives the same answer asinv(A) @ b, faster and more accurately.
When should you use it?
- Linear algebra exercises and formulas that need A⁻¹.
- Undoing a geometric transformation.
- Covariance and statistics formulas.
When not to use it
- Solving A x = b: use
np.linalg.solveinstead. - Matrices that are not square or are singular: use the pseudo-inverse
np.linalg.pinv.
Example code
import numpy as np
A = np.array([[4, 7],
[2, 6]], dtype=float)
A_inv = np.linalg.inv(A)
print("Inverse:")
print(A_inv.round(4))
# A matrix times its inverse gives the identity matrix
identity = A @ A_inv
print("A @ A_inv:")
print(identity.round(10) + 0.0) # + 0.0 turns -0.0 into 0.0
print("Is identity:", np.allclose(identity, np.eye(2)))
# The determinant must not be 0
print(f"Determinant: {np.linalg.det(A):.4f}")
# To solve A x = b, prefer np.linalg.solve over inv(A) @ b
b = np.array([1, 2], dtype=float)
print("inv(A) @ b:", (A_inv @ b).round(4).tolist())
print("solve(A, b):", np.linalg.solve(A, b).round(4).tolist())
Result of running the code
Inverse:
[[ 0.6 -0.7]
[-0.2 0.4]]
A @ A_inv:
[[1. 0.]
[0. 1.]]
Is identity: True
Determinant: 10.0000
inv(A) @ b: [-0.8, 0.6]
solve(A, b): [-0.8, 0.6]
Code explanation
np.linalg.inv(A) returns [[0.6, -0.7], [-0.2, 0.4]] for A = [[4, 7], [2, 6]]. A @ A_inv gives the 2 x 2 identity matrix, and np.allclose compares it with np.eye(2). Rounding can leave -0.0 in the result, so adding 0.0 prints it as 0. The determinant is 10, not 0, which is why the inverse exists. Both inv(A) @ b and np.linalg.solve(A, b) give [-0.8, 0.6], but solve is faster and more accurate, so use it whenever the goal is to solve A x = b.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Common mistakes
Using ** -1 for the inverse
On an array, ** -1 takes the reciprocal of each element, not the matrix inverse.
A_inv = A ** -1
A_inv = np.linalg.inv(A)
Multiplying with * instead of @
* multiplies element by element, so the identity check fails.
print(A * A_inv)
print(A @ A_inv)
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Matrix Multiplication Multiply two matrices, the operation behind every layer of a neural network. Easy
Tools for this lesson
- NumPy Matrix MultiplicationMultiply two matrices online with NumPy matmul and the @ operator.
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.