Level 1 Python: Pure Python Matrix Multiplication

Level 1 Python projects are projects that are more logically complex or require more libraries than the ones in the Super Simple Python series. Pure Python matrix multiplication is one of the projects that is more logically complex, we won’t be using any external libraries here. Most of these projects should take you between 30 to 45 minutes to build.

Matrix multiplication is an important part of linear algebra and machine learning. It’s actually quite easy to do in Python using the numpy library. However, it’s also useful to understand how matrix multiplication actually works. That’s why we’ll be taking a look at how we can do matrix multiplication with pure Python in this post.

In this post, we’ll cover:

  • Creating Some Example Matrices for Python matrix multiplication
  • Validate Matrices Being Multiplied
  • Pure Python Matrix Multiplication with Lists

Creating Some Example Matrices for Python Matrix Multiplication

In order to do matrix multiplication in pure Python, we’ll need to represent the matrices using native Python types. We’ll represent the matrices with lists of lists. Each entry in the outside list corresponds to a row in the matrix. Each entry in the inside list corresponds to a value in the matrix. 

For our example, we’ll create some square matrices to multiply for example. We’ll create two four by four matrices and two two by two matrices and multiply the four by fours by each other and the two by twos by each other.

mat_a = [[1, 2, 3, 4],
        [2, 4, 1, 3],
        [4, 2, 3, 1],
        [3, 1, 4, 2]]
mat_b = [[4, 2, 1, 3],
        [3, 4, 1, 2],
        [1, 2, 4, 3],
        [2, 1, 3, 4]]
# expected result:
# [[21, 20, 27, 32],
#  [27, 25, 19, 29],
#  [27, 23, 21, 29],
#  [23, 20, 26, 31]]
mat_c = [[1, 2],
        [2, 1]]
mat_d = [[3, 4],
        [4, 3]]
# expected result:
# [[11, 10],
#  [10, 11]]

Validate Matrices Being Multiplied

Before we attempt matrix multiplication, we should validate that it’s possible to multiply the matrices. An n x m matrix can only be multiplied by an m x p matrix. That means that the number of rows in the first matrix must be equal to the number of columns in the second matrix. This is due to the way that matrix multiplication works. When we multiply matrices, we sum the products of each row multiplied by each column.

We’ll create a validation function that takes two parameters. The first parameter is the first matrix and the second parameter is the second matrix. It’s important that these are in order because matrix multiplication is not commutative.

def validate(mat_a, mat_b):
   len_a = len(mat_a)
   len_b = len(mat_b[0])
   assert len_a == len_b

Pure Python Matrix Multiplication with Lists

Now that we’ve got some example matrices and a validation function, let’s create the function to actually do the matrix multiplication. Our matrix multiplication function will take two parameters. The first thing we’ll do is validate that the matrices can be multiplied. 

After validation, we’ll make matrix B easier to deal with in multiplication. To do this, we’ll zip it up into a tuple of tuples, and then wrap that in a list so we end up with a list of tuples. This is what allows us to easily access columns of B. 

Next, we’ll use list comprehension to do our pure Python matrix multiplication calculations. We’ll create a list of lists. The internal list is a sum of products for each entry in a row of A and a column of B for each column of B in the zipped iterable of matrix B. The external list is created based on each row of A in matrix A.

def mat_mul(mat_a, mat_b):
   validate(mat_a, mat_b)
   # turn matrix b into a list of tuples
   iterable_b = list(zip(*mat_b))
   return [[sum(a*b for a, b in zip(row_a, col_b)) for col_b in iterable_b] for row_a in mat_a]
print(mat_mul(mat_a, mat_b))
print(mat_mul(mat_c, mat_d))

This is what we should see in our output:

Python Matrix Multiplication Example Results
Pure Python Matrix Multiplication Results

Summary of Matrix Multiplication in Pure Python

In this post we learned how to do matrix multiplication with pure Python and no libraries. First we created a couple sets of matrices to multiply. Then we created a validation function to ensure that the two matrices passed to the function would be multipliable. Finally, we created a function to do the matrix multiplication using list comprehension and the zip function in Python.

Further Readings

I run this site to help you and others like you find cool projects and practice software skills. If this is helpful for you and you enjoy your ad free site, please help fund this site by donating below! If you can’t donate right now, please think of us next time.

Yujian Tang

7 thoughts on “Level 1 Python: Pure Python Matrix Multiplication

Leave a Reply

%d bloggers like this: