Python Program to Multiply Two Matrices
Intermediate · Matrices
Two matrices can be multiplied when the number of columns in the first equals the number of rows in the second. Each entry of the result is found by multiplying a row of the first matrix with a column of the second, item by item, and adding the products. This program multiplies a 2 x 3 matrix by a 3 x 2 matrix using nested loops.
Program
A x B = [58, 64] [139, 154]
How it works
- A matrix is stored as a list of rows, so
A[i][k]is the item in rowi, columnk. - The program first checks that the number of columns in
Amatches the number of rows inB. resultstarts as a matrix of zeros with as many rows asAand as many columns asB.- The innermost loop adds up
A[i][k] * B[k][j]for everyk, which is rowiofAtimes columnjofB. For example, the top-left entry is 1 x 7 + 2 x 9 + 3 x 11 = 58. - The list comprehension makes a separate list for each row;
[[0] * cols_b] * rows_awould make every row the same list.
Another way to write it
Using zip() and a list comprehension
A x B = [58, 64] [139, 154]
zip(*B) gives the columns of B, and zip(row, col) pairs up the numbers to multiply. It is compact, but the loop version is easier to follow.
Try it yourself
Multiply B by A instead and notice that the result is a 3 x 3 matrix, so the order of multiplication matters.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises