Linear Algebra with numpy.linalg
Reviewed & published by Brayan K
numpy.linalg is NumPy's linear-algebra submodule — a collection of fast, LAPACK-backed functions for determinants, matrix inverses, solving systems of equations, eigenvalues, and vector or matrix norms.
Part of the free NumPy course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
In this lesson you'll use np.linalg.det, np.linalg.inv, np.linalg.solve, np.linalg.eig, and np.linalg.norm to do real linear algebra in a few lines of code.
What You'll Learn in This Lesson
- Compute a determinant with np.linalg.det
- Find a matrix inverse with np.linalg.inv
- Solve a system Ax = b with np.linalg.solve
- Get eigenvalues and eigenvectors with np.linalg.eig
- Measure magnitude with np.linalg.norm
- Why solve() beats inv() for accuracy and speed
1 The Determinant: np.linalg.det
The determinant is a single number computed from a square matrix. It tells you whether the matrix is invertible: if the determinant is zero, the matrix is singular and has no inverse. For a 2×2 matrix [[a, b], [c, d]] the determinant is simply a*d − b*c.
import numpy as np
A = np.array([[4, 7],
[2, 6]])
det = np.linalg.det(A)
print(round(det, 2)) # 10.0 (because 4*6 - 7*2 = 24 - 14 = 10)
# A singular matrix has determinant 0 (its rows are multiples of each other)
B = np.array([[1, 2],
[2, 4]])
print(round(np.linalg.det(B), 2)) # 0.0 -> no inverse exists
# ✅ Expected output:
# 10.0
# 0.0Expected output: 10.0 then 0.0. The second matrix is singular because its second row is exactly twice the first.
2 The Inverse: np.linalg.inv
The inverse of a matrix A is the matrix A⁻¹ such that A @ A⁻¹ equals the identity matrix. Only square, non-singular matrices have an inverse. np.linalg.inv computes it for you.
import numpy as np
A = np.array([[4, 7],
[2, 6]])
A_inv = np.linalg.inv(A)
print(np.round(A_inv, 2))
# [[ 0.6 -0.7 ]
# [-0.2 0.4 ]]
# A multiplied by its inverse gives the identity matrix
identity = A @ A_inv
# The right way to check: floating-point maths lands on values like 1.0 and
# ±1.1e-16, never exact 0. allclose compares within a tolerance.
print(np.allclose(identity, np.eye(2)))
# Printing it needs one more step. Rounding those tiny values gives -0.0 as
# often as 0.0 — which sign you get is decided by the BLAS library your NumPy
# was built against, so it differs between machines. Adding 0.0 turns every
# -0.0 back into 0.0 and leaves real numbers alone.
print(np.round(identity, 2) + 0.0)
# ✅ Expected output:
# [[ 0.6 -0.7]
# [-0.2 0.4]]
# True
# [[1. 0.]
# [0. 1.]]Expected output: the inverse matrix, and A @ A_inv rounded to the 2×2 identity [[1. 0.] [0. 1.]].
3 Solving Systems: np.linalg.solve(A, b)
A system of linear equations can be written as A x = b, where A is a matrix of coefficients, b is the right-hand side, and x is the unknown vector. np.linalg.solve(A, b) returns x directly.
import numpy as np
# Solve: 3x + 2y = 12
# 1x + 1y = 5
A = np.array([[3, 2],
[1, 1]])
b = np.array([12, 5])
x = np.linalg.solve(A, b)
print(x) # [2. 3.] -> x = 2, y = 3
# Verify by plugging the solution back in
print(A @ x) # [12. 5.] -> matches b exactly
# ✅ Expected output:
# [2. 3.]
# [12. 5.]Expected output: [2. 3.] (so x = 2, y = 3), and A @ x reproduces [12. 5.].
4 Eigenvalues (np.linalg.eig) & Norms (np.linalg.norm)
An eigenvector is a direction the matrix only stretches or shrinks; the stretch factor is its eigenvalue. np.linalg.eig returns (eigenvalues, eigenvectors). Separately, np.linalg.norm measures a vector's length — by default the Euclidean (L2) norm, the square root of the sum of squared elements.
import numpy as np
A = np.array([[2, 0],
[0, 3]])
eigenvalues, eigenvectors = np.linalg.eig(A)
print(eigenvalues) # [2. 3.]
print(eigenvectors)
# [[1. 0.]
# [0. 1.]]
v = np.array([3, 4])
print(np.linalg.norm(v)) # 5.0 (sqrt(3**2 + 4**2))
print(np.linalg.norm(np.array([6, 8]))) # 10.0
print(np.round(v / np.linalg.norm(v), 2)) # [0.6 0.8] (unit vector)
# ✅ Expected output:
# [2. 3.]
# [[1. 0.]
# [0. 1.]]
# 5.0
# 10.0
# [0.6 0.8]Expected output: eigenvalues [2. 3.] with the identity as eigenvectors, then 5.0, 10.0, and the unit vector [0.6 0.8].
🎯 YOUR TURN: Fill in the Blanks
Replace each ___ so the program solves the system 2x + y = 5, x + 3y = 10.
import numpy as np
A = np.array([[2, 1],
[1, 3]])
b = np.array([5, 10])
x = np.linalg.___(A, b) # fill in the function that solves A x = b
print(x) # Expected output: [1. 3.]Expected output: [1. 3.]. (Answer: solve.)
⚠️ Common Errors & Quick Reference
You tried to invert or solve with a matrix whose determinant is 0.
✅ Fix: check np.linalg.det(A) first; a singular system has no unique solution.
❌ LinAlgError: Last 2 dimensions of the array must be square
Most linalg functions require a square matrix (same number of rows and columns).
✅ Fix: confirm A.shape is (n, n) before calling det, inv, solve, or eig.
| Task | Code |
|---|---|
| Determinant | np.linalg.det(A) |
| Inverse | np.linalg.inv(A) |
| Solve A x = b | np.linalg.solve(A, b) |
| Eigenvalues/vectors | np.linalg.eig(A) |
| Vector norm | np.linalg.norm(v) |
🏆 Mini Challenge: Coffee Shop Order
Two orders: 2 coffees + 1 muffin cost $11, and 1 coffee + 2 muffins cost $10. Find the price of one coffee and one muffin by solving the system.
import numpy as np
# 2c + 1m = 11
# 1c + 2m = 10
A = np.array([[2, 1],
[1, 2]])
b = np.array([11, 10])
prices = np.linalg.solve(A, b)
print(prices) # [4. 3.] -> coffee = $4, muffin = $3
print("Coffee:", prices[0]) # Coffee: 4.0
print("Muffin:", prices[1]) # Muffin: 3.0
# ✅ Expected output:
# [4. 3.]
# Coffee: 4.0
# Muffin: 3.0❓ Frequently Asked Questions
Lesson complete — you can do linear algebra!
You computed determinants and inverses, solved a system of equations with np.linalg.solve, found eigenvalues, and measured vectors with np.linalg.norm.
Practice quiz
Which function computes the determinant of a square matrix?
- np.linalg.det
- np.linalg.norm
- np.linalg.solve
- np.linalg.eig
Answer: np.linalg.det. np.linalg.det returns the single determinant value of a square matrix.
What is the determinant of [[4, 7], [2, 6]]?
- 38
- 10.0
- 0.0
- 24
Answer: 10.0. For a 2x2 matrix it is a*d - b*c = 4*6 - 7*2 = 24 - 14 = 10.
Why is np.linalg.solve(A, b) preferred over np.linalg.inv(A) @ b?
- It returns more digits
- It works on non-square matrices
- It is faster and more numerically accurate
- It is the only one that exists
Answer: It is faster and more numerically accurate. solve never forms the full inverse, so it is faster and avoids extra rounding error.
What does np.linalg.solve(np.array([[3,2],[1,1]]), np.array([12,5])) return?
- [5. 2.]
- [3. 2.]
- [2. 3.]
- [12. 5.]
Answer: [2. 3.]. The system gives x = 2, y = 3, printed as [2. 3.].
What does np.linalg.norm([3, 4]) return?
- 7.0
- 12.0
- 1.0
- 5.0
Answer: 5.0. The default Euclidean norm is sqrt(3**2 + 4**2) = sqrt(25) = 5.0.
A matrix whose determinant is 0 is described as what?
- Singular (no inverse)
- Orthogonal
- Symmetric
- Invertible
Answer: Singular (no inverse). A zero determinant means the matrix is singular and has no inverse.
What does np.linalg.eig return?
- Only eigenvalues
- A tuple of (eigenvalues, eigenvectors)
- Only eigenvectors
- A determinant
Answer: A tuple of (eigenvalues, eigenvectors). eig returns both eigenvalues and eigenvectors as a tuple.
For the diagonal matrix [[2,0],[0,3]], the eigenvalues are:
- [5. 6.]
- [0. 0.]
- [2. 3.]
- [6. 6.]
Answer: [2. 3.]. A diagonal matrix has its diagonal entries as eigenvalues: [2. 3.].
What does A @ np.linalg.inv(A) give for an invertible A?
- The zero matrix
- The transpose of A
- A doubled
- The identity matrix
Answer: The identity matrix. A times its inverse yields the identity matrix.
Which error is raised when you invert a singular matrix?
- LinAlgError: Singular matrix
- IndexError
- KeyError
- OverflowError
Answer: LinAlgError: Singular matrix. Inverting a determinant-zero matrix raises LinAlgError: Singular matrix.
Continue this course
- Previous: Random Number Generation
- Next: Matrix Operations & Dot Products — Multiply matrices with dot and the @ operator
- Quick reference: NumPy cheat sheet › Linear Algebra & Random
Frequently asked questions
What does numpy.linalg do?
numpy.linalg is NumPy's linear-algebra submodule. It provides fast routines for determinants, matrix inverses, solving systems of linear equations, eigenvalues and eigenvectors, vector and matrix norms, and more — all built on optimized LAPACK code.
Should I use np.linalg.solve or np.linalg.inv to solve Ax = b?
Use np.linalg.solve(A, b). It is both faster and more numerically accurate than computing inv(A) @ b, because it never forms the full inverse and avoids the extra rounding error that inverting a matrix introduces.
Why does np.linalg.inv raise LinAlgError?
It raises numpy.linalg.LinAlgError: Singular matrix when the matrix has no inverse — its determinant is zero (or numerically very close to zero). Singular matrices represent systems with no unique solution.
What is np.linalg.norm used for?
np.linalg.norm measures the 'length' or magnitude of a vector or matrix. By default it returns the Euclidean (L2) norm of a vector, the square root of the sum of squared elements, which is useful for distances, normalization, and error measurements.