Moving past special matrices, there are some more advanced linear algebra operations we can perform using NumPy. To start, we will be using the numpy.linalg sublibrary to perform the following operations:

The “norm” (or length/magnitude) of a vector can be found using np.linalg.norm():

v = np.array([2,-4,1]) v_norm = np.linalg.norm(v)

This outputs v_norm as:


The inverse of a square matrix, if one exists, can be found using np.linalg.inv():

A = np.array([[1,2],[3,4]]) print(np.linalg.inv(A))

This outputs:

[[-2. 1. ] [ 1.5 -0.5]]

Finally, we can actually solve for unknown variables in a system on linear equations in Ax=b form using np.linalg.solve(), which takes in the A and b parameters. Given:

x + 4y - z = -1 -x - 3y + 2z = 2 2x - y - 2z = -2

We convert to Ax=b form and solve.

# each array in A is an equation from the above system of equations A = np.array([[1,4,-1],[-1,-3,2],[2,-1,-2]]) # the solution to each equation b = np.array([-1,2,-2]) # solve for x, y, and z x,y,z = np.linalg.solve(A,b)

If we print((x, y, z)), we see the following output:

(0, 0, 1.0)

showing that the solution to the system of equations is:

x = 0 y = 0 z = 1



We have a system of equations written out for us in script.py. Let’s put this in the form Ax=b and solve the system using NumPy.

First, let’s define A using a NumPy array. Save this NumPy array in a variable called A. When you define A, pay attention to the coefficients in each equation.

If you get stuck, click the hint for some guidance.


We now need the b part of our Ax=b form.

Create a NumPy array in a variable named b that represents the system of equations given.


Use np.linalg.solve() to solve Ax=b. Use the variables x, y, and z to represent the solutions.

After using np.linalg.solve(), use the following line of code to view the solution to the system of equations:


Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?