Python Program to Add Two Matrices

« Previous Program Next Program »

Add Two Matrices in Python

To add two matrices in python, you have to choose two matrix and another empty matrix. The third or empty matrix is used to store the addition result of the two matrices as shown in the program given below.

Python Programming Code to Add Two Matrices

Following python program adds two matrices to print the addition result of the two matrices:

# Python Program - Add Two Matrices
matrix1 = [[1, 2, 3],
	   [4, 5, 6],
	   [7, 8, 9]]
matrix2 = [[10, 11, 12],
	   [13, 14, 15],
	   [16, 17, 18]]
rmatrix = [[0, 0, 0],
	   [0, 0, 0],
	   [0, 0, 0]]
for i in range(len(matrix1)):
    for j in range(len(matrix1[0])):
        rmatrix[i][j] = matrix1[i][j] + matrix2[i][j]
for r in rmatrix:

Here is the sample run of the above Python program shows how to add two matrices:

Adding of two matrices can be performed using matrix1[0][0] + matrix2[0][0] or 1+10, matrix1[0][1] + matrix[0][1] or 2+11, matrix1[0][2] + matrix2[0][2] or 3+12, matrix1[1][0] + matrix[1][0] or 4+13 and so on. Here the result of additing the matrix1 and matrix2 will be the third matrix, that is rmatrix[0][0] holds 11, rmatrix[0][1] holds 13 and so on.

add two matrices python

Here is the same program on python shell:

python add two matrices

Same Program in Other Languages

You may also like to learn or practice the same program in other popular programming languages:

« Previous Program Next Program »


Quick Links
Signup - Login - Give Online Test