BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Python Program to Add two Matrices

Last Updated: March 21, 2018 by Chaitanya Singh | Filed Under: Python Examples

In this article, we will see how to add two matrices in Python. Before we see how to implement matrix addition in Python, lets see what it looks like:

M1 = [[1,1,1],
      [1,1,1],
      [1,1,1]]
 
M2 = [[1,2,3],
      [4,5,6],
      [7,8,9]]
 
Sum of these matrices:
   = [[2,3,4],
      [5,6,7],
      [8,9,10]]

Program for adding two matrices

To represent a matrix, we are using the concept of nested lists. All the elements of both the input matrices are represented as nested lists. All the elements of output list are initialized as zero.

We are iterating the matrix and adding the corresponding elements of both the given matrices and assigning the value in the output matrix.

# This program is to add two given matrices
# We are using the concept of nested lists to represent matrix

# first matrix
M1 = [[1, 1, 1],
      [1, 1, 1],
      [1, 1, 1]]

# second matrix
M2 = [[1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]]

# In this matrix we will store the sum of above matrices
# we have initialized all the elements of this matrix as zero
sum = [[0, 0, 0],
       [0, 0, 0],
       [0, 0, 0]]

# iterating the matrix
# rows: number of nested lists in the main list
# columns: number of elements in the nested lists
for i in range(len(M1)):
    for j in range(len(M1[0])):
        sum[i][j] = M1[i][j] + M2[i][j]

# displaying the output matrix
for num in sum:
    print(num)

Output:

[2, 3, 4]
[5, 6, 7]
[8, 9, 10]

Related Python Examples

  1. Python Program to add two binary numbers
  2. Python Program to find factorial of number
  3. Python Program to check leap year
  4. Python Program to add two numbers
  5. Python program to print Hello World

Top Related Articles:

  1. Python Program to Find Factorial of Number
  2. Python Program to Add Digits of a Number
  3. Python Program to Check if a Number is Positive Negative or Zero
  4. Python Program to Add Subtract Multiply and Divide two numbers
  5. Python Program to Find ASCII Value of a Character

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap