Home / Python / Example programs / Lists

Python program: Multiply two matrices

Multiply matrices stored as lists of lists, then check with NumPy.

The code

A = [[1, 2],
     [3, 4]]
B = [[5, 6],
     [7, 8]]

result = [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))]
print(result)

import numpy as np
print(np.array(A) @ np.array(B))

Output

[[19, 22], [43, 50]]
[[19 22]
 [43 50]]

How it works

Each cell is the sum of a row of A times a column of B. NumPy's @ does it for you, and very fast: that is the operation at the heart of neural networks.

Python features used

Learn the ideas behind it in the free lesson Numpy.