PythonMastery
Python programs · Lists · intermediate

Matrix multiplication in Python

Multiply two matrices stored as nested lists with three nested loops, check first that their shapes fit, then see a shorter version with zip().

To multiply matrix A by matrix B, each number in the result comes from one row of A and one column of B: multiply the pairs of numbers and add them up. This only works when A has as many columns as B has rows.

The program

python
def multiply_matrices(a, b):
    rows_a, cols_a = len(a), len(a[0])
    rows_b, cols_b = len(b), len(b[0])
    if cols_a != rows_b:
        raise ValueError(f"cannot multiply a {rows_a} by {cols_a} matrix by a {rows_b} by {cols_b} matrix")

    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]
    return result

A = [[1, 2, 3],
     [4, 5, 6]]
B = [[7, 8],
     [9, 10],
     [11, 12]]

for row in multiply_matrices(A, B):
    print(row)

try:
    multiply_matrices(A, A)
except ValueError as error:
    print("Error:", error)
output
[58, 64]
[139, 154]
Error: cannot multiply a 2 by 3 matrix by a 2 by 3 matrix

How it works

Another way: zip()

zip(*b) gives the columns of b (this is the transpose). Then each result number is the sum of one row of A times one column of B:

python
def multiply_matrices(a, b):
    if len(a[0]) != len(b):
        raise ValueError("the columns of a must match the rows of b")
    columns = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in columns] for row in a]

A = [[1, 2, 3],
     [4, 5, 6]]
B = [[7, 8],
     [9, 10],
     [11, 12]]

print(multiply_matrices(A, B))
print(multiply_matrices(B, A))
output
[[58, 64], [139, 154]]
[[39, 54, 69], [49, 68, 87], [59, 82, 105]]

Adding two matrices is simpler, because the numbers in the same position are added: see matrix addition. For large matrices, the NumPy library multiplies two arrays with A @ B, much faster than Python loops.

Learn the idea: Lists & Sequences, Loops: for, while, and the Pythonic Patterns, Comprehensions: Lists, Dicts, Sets, Generators