A matrix is a grid of numbers. In plain Python it is a list of rows, and each row is a list. To add two matrices of the same shape, add the numbers that are in the same row and column.
The program
python
def add_matrices(a, b): if len(a) != len(b) or any(len(row_a) != len(row_b) for row_a, row_b in zip(a, b)): raise ValueError("the matrices must have the same number of rows and columns") result = [] for row_a, row_b in zip(a, b): result.append([x + y for x, y in zip(row_a, row_b)]) return result A = [[1, 2, 3], [4, 5, 6]] B = [[10, 20, 30], [40, 50, 60]] C = add_matrices(A, B) for row in C: print(row)
output
[11, 22, 33] [44, 55, 66]
How it works
- The outer
zip(a, b)takes one row from each matrix at a time: first[1, 2, 3]with[10, 20, 30], then the second rows. - The inner
zip(row_a, row_b)pairs the numbers in the same column, and the list comprehension adds each pair. zip()stops at the end of the shorter list without an error. So without the shape check, adding a 2 by 3 matrix to a 2 by 2 matrix would quietly give a wrong 2 by 2 answer. The first line of the function raises aValueErrorinstead.
Different shapes
python
def add_matrices(a, b): if len(a) != len(b) or any(len(row_a) != len(row_b) for row_a, row_b in zip(a, b)): raise ValueError("the matrices must have the same number of rows and columns") return [[x + y for x, y in zip(row_a, row_b)] for row_a, row_b in zip(a, b)] try: add_matrices([[1, 2, 3], [4, 5, 6]], [[1, 2], [3, 4]]) except ValueError as error: print("Error:", error)
output
Error: the matrices must have the same number of rows and columns
This version builds the result with one nested list comprehension. For large matrices, the NumPy library adds two arrays with A + B. The NumPy lesson covers it.