Add Two Matrices Python (original) (raw)

Last Updated : 1 Nov, 2025

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:

matrics

Two 2x2 Matrices

The sum of these matrices would be:

matrics_output

Addition of the above matrices

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.

Python `

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:

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.

Python `

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:

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.

Python `

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: