Program to Add Two Matrices in Python. This program contains matrices assignment, Nested for loop, Arithmetic operation and print statement. This is for Beginners, class 11,12 and B Tech computer science students.
Program to Add Two Matrices
What is Matrix?
In mathematics, matrix is a rectangular array of numbers, symbols or expressions arranged in the form of rows and columns. For example: if you take a matrix A which is a 2×3 matrix then it can be shown like this:
- 2 3 5
- 8 12 7
Image representation:

In Python, matrices can be implemented as nested list. Each element of the matrix is treated as a row. For example X = [[1, 2], [3, 4], [5, 6]] would represent a 3×2 matrix. First row can be selected as X[0] and the element in first row, first column can be selected as X[0][0].
Source code :
X = [[1,2,3],
[4,5,6],
[7,8,9]]
Y = [[10,11,12],
[13,14,15],
[16,17,18]]
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)
Source code Explanation:
Step 1 : intialisation of matrices.
X = [[1,2,3],
[4,5,6],
[7,8,9]]
Y = [[10,11,12],
[13,14,15],
[16,17,18]]
step 2 : third matrices
result = [[0,0,0],
[0,0,0],
[0,0,0]]
step 3: iterate through rows
for i in range(len(X)):
step 4: 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 :
>>> RESTART: C:/csstudy/source code file 2/Program to Add Two Matrices in Python.py [11, 13, 15] [17, 19, 21] [23, 25, 27] >>>
Output Explanation:
RESTART: C:/csstudy/source code file 2/Program to Add Two Matrices in Python.py
[11, 13, 15]
[17, 19, 21]
[23, 25, 27]
Conclusion :
The program is running fine.
Thank you for reading, learning and download source code of Program to Add Two Matrices in Python. This program contains matrices assignment, Nested for loop, Arithmetic operation and print statement. This is for Beginners, class 11,12 and B Tech computer science students. Below are the links provided for more programs, practical file of class 11 ,12 and python projects.
/category/python-programs/
Computer Science with Python Practical Book Solutions Class 11 Term -2 – CS Study
Computer Science Practical file for class 12 Term-2 – CS Study
Python Projects for Class 12 with Source Code (Mysql Connectivity) – CS Study