# Python Program to Add Two Matrices taking User Input

Summary:

Problem: Write a Python program to add two matrices by taking input from the user.

Description: The rule to add two matrices is to add the elements on the same rows and columns number. Open Image

Note: Both matrices must have the same number of rows and columns.

Example:

``````Input:
[[1 2 3]
[4 5 6]]

[[4 5 6]
[7 8 9]]

Output:
[[5 7 9]
[11 13 15]]

Explanation:
[[1+4 2+5 3+6]
[4+7 5+8 6+9]]``````

Hint: In Python, we use nested List to represent 2d Matrix. Iterate through each nested list and add the result to a new result list.

You should try to write the Python program to add two matrices on your own before moving to the solution.

## Python Program Add two Matrices Using for loop

Copy

``````matrix1 = [
[1, 2, 3],
[4, 5, 6]
]
#Uncomment to take Input
#matrix1 = [list(map(int,input("Enter the row value separated by space: ").split(" "))) for i in range(int(input("Enter Number of rows: ")))]

matrix2 = [
[2, 3, 4],
[5, 6, 7]
]

#matrix2 = [list(map(int,input("Enter the row value separated by space: ").split(" "))) for i in range(int(input("Enter Number of rows: ")))]

result = [
[0, 0, 0],
[0, 0, 0]
]
#Iterate Rows
for i in range(len(result)):
#Iterate columns
for j in range(len(result[i])):
result[i][j] = matrix1[i][j]+matrix2[i][j]

print(result)``````

Output

[[3, 5, 7], [9, 11, 13]]

The logic of the program is easy if you know how to add two matrices.

We iterate through rows and columns of any matrix and add each element one by one in the result list.

You can uncomment the input code to take the matrix from the user. It uses the list comprehension to create a nested list.

## Python Program: Add matrices using List Comprehension

You must know list comprehension to understand the code.

Copy

``````matrix1 = [list(map(int,input("Enter the row value separated by space: ").split(" "))) for i in range(int(input("Enter Number of rows: ")))]
matrix2 = [list(map(int,input("Enter the row value separated by space: ").split(" "))) for i in range(int(input("Enter Number of rows: ")))]
result = [[matrix1[i][j]+matrix2[i][j] for j in range(len(matrix1))] for i in range(len(matrix1))]
print(result)``````

Output

Enter Number of rows of matrix1: 2 Enter the row value separated by space: 1 2 3 Enter the row value separated by space: 4 5 6 Enter Number of rows of matrix2: 2 Enter the row value separated by space: 2 3 4 Enter the row value separated by space: 5 6 7 [[3, 5, 7], [9, 11, 13]]

You must avoid nested list comprehension like this in your code because it makes the code hard to understand.