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
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)
[58, 64] [139, 154] Error: cannot multiply a 2 by 3 matrix by a 2 by 3 matrix
How it works
- A is 2 by 3 (2 rows, 3 columns) and B is 3 by 2. The 3 columns of A match the 3 rows of B, so the result is 2 by 2: the rows of A by the columns of B.
ipicks the row of A,jpicks the column of B, andkwalks along both. For the top-left number: 1×7 + 2×9 + 3×11 = 58.[[0] * cols_b for _ in range(rows_a)]makes a separate list for each row. Do not write[[0] * cols_b] * rows_a: that repeats the same inner list, so changing one row would change all of them.- The order matters. A×B is 2 by 2, but B×A is 3 by 3, and A×A is not possible, as the error shows.
- The code assumes every row of a matrix has the same length, as a real matrix does.
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:
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))
[[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.