Add Two Matrices - Python
The task of adding two matrices in Python involves combining corresponding elements from two given matrices to produce a new matrix. Each element in the resulting matrix is obtained by adding the values at the same position in the input matrices.
For example, if two 2x2 matrices are given as:

The sum of these matrices would be:

Let's explore the various ways of adding two matrices in Python.
Using NumPy
NumPy is the most efficient solution for adding two matrices in Python. It is designed for high-performance numerical operations and matrix addition is natively supported using vectorized operations. With NumPy, we can simply use the '+' operator for matrix addition.
import numpy as np
a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]])
res = a + b
print(res)
Output
[[10 10 10] [10 10 10] [10 10 10]]
Explanation:
- a and b are two 3x3 NumPy arrays.
- '+' operator applies element-wise addition using vectorization, making it fast and clean.
- this approach avoids manual looping, making your code more concise and efficient.
Using list comprehension
List comprehension is a faster alternative to traditional loops when adding two matrices. It allows performing element-wise operations in a single line, improving readability and execution speed, especially for small to medium-sized matrices.
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
res = [[a[i][j] + b[i][j] for j in range(len(a[0]))] for i in range(len(a))]
for r in res:
print(r)
Output
[10, 10, 10] [10, 10, 10] [10, 10, 10]
Explanation:
- Outer list comprehension iterates over rows.
- Inner list comprehension iterates over columns.
- Performs element-wise addition without explicit nested loops.
Using Nested Loops
The traditional nested loop method is the most basic approach to adding two matrices. It manually iterates through each element of the matrices, making it clear for beginners but less efficient and slower for larger datasets compared to modern alternatives.
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
b = [[9, 8, 7], [6, 5, 4], [3, 2, 1]]
res = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
for i in range(len(a)):
for j in range(len(a[0])):
res[i][j] = a[i][j] + b[i][j]
for r in res:
print(r)
Output
[10, 10, 10] [10, 10, 10] [10, 10, 10]
Explanation:
- Outer loop (for i in range(len(a))): Iterates through each row index of matrix a.
- Inner loop (for j in range(len(a[0]))): Iterates through each column index of matrix a.
- res[i][j] = a[i][j] + b[i][j]: Adds corresponding elements from both matrices and stores them in res.