Menu Close
Python program to add two matrices

Python Program To Add Two Matrices

In this article, we are going to write 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 following Python Programming topics.

Add two matrices using nested loop:-

In this example we have two matrix X and Y of dimension 3 X 3 and we created a 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 above example we have used nested for loop to iterate each rows and each columns. At each point we added the corresponding elements in the matrix and store in the result.

Add Two matrices using list comprehension

In this example add two matrix 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 above program we have used list comprehension to add elements of two matrix.

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 second is list comprehension.
I hope this article will help you. if you like article please comment and share with your friends who want to learn Python examples.

For More Information:- Click Here

Previous Article
Next Article

Was this post helpful?

Related Posts

Leave a Reply