Program to add and print two matrices using Python


In this section of the python programming, our task is to perform arithmetic addition of two matrices and print the resultant matrix. While the addition of matrices we should keep in mind that the two matrices can only be added if they are of same size.

Expression: sum[i][j] = X[i][j] + Y[i][j]

Program to add and print two matrices


mat1 = [[2,3,1], [7,4,5], [5,1,1]]
mat2 = [[7,2,1], [9,0,4], [2,0,0]]
sum_mat = [[0,0,0], [0,0,0], [0,0,0]]

# Using list comprehension
sum_matrix = [[mat1[i][j] + mat2[i][j] for j in range (len(mat1[0]))] for i in range(len(mat1))]
print("Sum using list comprehension:")
for ele in sum_matrix:
# Using loop
for i in range(len(mat1)):
    for j in range(len(mat1[0])):
        sum_mat[i][j] = mat1[i][j] + mat2[i][j]
print("Sum using loop:")
for val in sum_mat:


Program to add and print two matrices Output


In the above python code, we used two ways to add the elements of matrices.

The first one is a list comprehension, we used nested list (list inside list) comprehension and added the corresponding elements and stored in sum_matrix.

The second one is the loop. In loop we have nested loop to iterate through each row and columns and simultaneously adding the corresponding elements of the matrices.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.