Editor

Python Program to Add Two Matrices

Beginner · Matrices

Two matrices can be added when they have the same number of rows and columns. Each entry of the result is the sum of the entries in the same position, so result[i][j] = A[i][j] + B[i][j]. This program adds two 3 x 3 matrices with nested loops and prints all three, row by row.

Program

add_two_matrices.py
def print_matrix(matrix):
for row in matrix:
for value in row:
print(f"{value:4}", end="") # each number takes 4 spaces
print()
A = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
B = [[5, 1, 0],
[2, 7, 3],
[4, 6, 8]]
result = []
for i in range(len(A)): # each row
row = []
for j in range(len(A[0])): # each column
row.append(A[i][j] + B[i][j])
result.append(row)
print("Matrix A:")
print_matrix(A)
print("Matrix B:")
print_matrix(B)
print("A + B:")
print_matrix(result)
Output
Matrix A:
   1   2   3
   4   5   6
   7   8   9
Matrix B:
   5   1   0
   2   7   3
   4   6   8
A + B:
   6   3   3
   6  12   9
  11  14  17

How it works

  1. A matrix is stored as a list of rows, so A[i][j] is the entry in row i, column j.
  2. The outer loop goes through the rows and the inner loop through the columns of each row.
  3. Each pair of matching entries is added and appended to row, and each finished row is appended to result.
  4. print_matrix() prints each row on its own line, and {value:4} gives every number four spaces so the columns line up.

Other ways to write it

Using zip() and a list comprehension

Using zip() and a list comprehension
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [[5, 1, 0], [2, 7, 3], [4, 6, 8]]
result = [[a + b for a, b in zip(row_a, row_b)] for row_a, row_b in zip(A, B)]
print("A + B:")
for row in result:
print(row)
Output
A + B:
[6, 3, 3]
[6, 12, 9]
[11, 14, 17]

The outer zip() pairs up the rows of A and B, and the inner one pairs up the numbers in each pair of rows.

Subtracting two matrices

Subtracting two matrices
A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
B = [[5, 1, 0], [2, 7, 3], [4, 6, 8]]
rows = len(A)
cols = len(A[0])
result = [[A[i][j] - B[i][j] for j in range(cols)] for i in range(rows)]
print("A - B:")
for row in result:
print(row)
Output
A - B:
[-4, 1, 3]
[2, -2, 3]
[3, 2, 1]

Subtraction works the same way, entry by entry, with - instead of +.

Try it yourself

Add a check that prints a message when the two matrices do not have the same number of rows and columns.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises