PythonMastery
Python programs · Lists · beginner

Matrix addition in Python

Add two matrices stored as nested lists in Python: add the numbers in the same row and column, and check first that both have the same shape.

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

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.

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