Editor

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

matrix_multiplication.py
# A is 2 x 3 and B is 3 x 2, so A x B is 2 x 2
A = [[1, 2, 3],
[4, 5, 6]]
B = [[7, 8],
[9, 10],
[11, 12]]
rows_a = len(A)
cols_a = len(A[0])
cols_b = len(B[0])
if cols_a != len(B):
print("Cannot multiply: columns of A must equal rows of B")
else:
# Start with a result matrix full of zeros
result = [[0] * cols_b for _ in range(rows_a)]
for i in range(rows_a):
for j in range(cols_b):
for k in range(cols_a):
result[i][j] += A[i][k] * B[k][j]
print("A x B =")
for row in result:
print(row)
Output
A x B =
[58, 64]
[139, 154]

How it works

  1. A matrix is stored as a list of rows, so A[i][k] is the item in row i, column k.
  2. The program first checks that the number of columns in A matches the number of rows in B.
  3. result starts as a matrix of zeros with as many rows as A and as many columns as B.
  4. The innermost loop adds up A[i][k] * B[k][j] for every k, which is row i of A times column j of B. For example, the top-left entry is 1 x 7 + 2 x 9 + 3 x 11 = 58.
  5. The list comprehension makes a separate list for each row; [[0] * cols_b] * rows_a would make every row the same list.

Another way to write it

Using zip() and a list comprehension

Using zip() and a list comprehension
A = [[1, 2, 3], [4, 5, 6]]
B = [[7, 8], [9, 10], [11, 12]]
# zip(*B) gives the columns of B
result = [[sum(a * b for a, b in zip(row, col)) for col in zip(*B)] for row in A]
print("A x B =")
for row in result:
print(row)
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises