Menu Close
Python program to add two matrices

In this article, we are going to write a Python program to add two matrices. In this Python examples tutorial, we will see two different ways to add elements of two matrices first is nested loop and the second is list comprehension.

To understand this example you should have basic knowledge of the following Python programming topics.

Add two matrices using a nested loop:-

In this example, we have two matrices X and Y of dimension 3 X 3 and we created an empty matrix to store the result.

Example:


# Python program to add two matrices using nested for loop.
x = [[12, 7, 3],
	[4, 8, 10],
	[12, 23, 10]]

y = [[13, 7, 3],
	[6, 8, 5],
	[12, 5, 10]]

result =[[0, 0, 0],
	  [0, 0, 0],
	  [0, 0, 0]]

#iterate through rows
for i in range(len(x)):
    #iterate through columns
	for j in range(len(x[0])):
		result[i][j] = x[i][j] + y[i][j]


for r in result:
	print(r)

Output

[25, 14, 6]
[10, 16, 15]
[24, 28, 20]

In the above example, we have used a nested for loop to iterate each row and each column. At each point, we added the corresponding elements in the matrix and store them in the result.

Add two matrices using list comprehension

In this example add two matrices using nested list comprehension:


#Python program to add two matrix using list comprehension.
x = [[12, 7, 3],
	[4, 8, 10],
	[12, 23, 10]]

y = [[13, 7, 3],
	[6, 8, 5],
	[12, 5, 10]]

result = [[x[i][j] + y[i][j]  for j in range(len(x[0]))] for i in range(len(x))]
for r in result:
   print(r)

Output

[25, 14, 6]
[10, 16, 15]
[24, 28, 20]

In the above program, we have used list comprehension to add elements of two matrices.

Conclusion:

In this tutorial, You have learned how to add two matrices using Python. Here we have seen two ways to add two matrices first is nested for loop and the second is list comprehension.
I hope this article will help you. if you like the article please comment and share it with your friends who want to learn Python examples.

For More Information:- Click Here

Python Program To Add Two Numbers
Python Program to Count and Display Consonants from a String

Related Posts