# Matrix multiplication with Python list comprehensions.

Multiplying two matrixes can be done easily with numpy. But did you know Python can do it in one line of code with list comprehensions?

Here are two matrices that are multiplied with the result:

1 2 3 10 20 30 40 380 440 500 560 4 5 6 . 50 60 70 80 = 830 980 1130 1280 7 8 9 90 100 110 120 1280 1520 1760 2000 10 11 12 1730 2060 2390 2720

Here is the Python code that multipies the matrices:

product = [[sum(a * b for a, b in zip(aa, bb)) for bb in BT] for aa in A]

Matrix A and matrix BT need to have the same dimensions and the same orientation (rotation). Here is a full example:

A = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12] ] B = [ [10, 20, 30, 40], [50, 60, 70, 80], [90, 100, 110, 120] ] BT = list(zip(*B)) # transpose B assert(len(A) == len(BT)) # assert that dimensions assert(len(A[0]) == len(BT[0])) # of A and BT are the same product = [[sum(a * b for a, b in zip(aa, bb)) for bb in BT] for aa in A] for p in product: print(p)

## Result:

[380, 440, 500, 560] [830, 980, 1130, 1280] [1280, 1520, 1760, 2000] [1730, 2060, 2390, 2720]

In an earlier post, I showed how to transpose a matrix with list comprehensions. It turns out that zip(*MATRIX) also transposes a matrix.

Written by

**Loek van den Ouweland**on 2021-12-03. Questions regarding this artice? You can send them to the address below.