Tuesday, October 3, 2023
HomeProgrammingPythonPython 3 Program To Add Two Matrices

# Python 3 Program To Add Two Matrices

This post was last Updated on June 8, 2023 by Himanshu Tyagi to reflect the accuracy and up-to-date information on the page.

Here you will learn a simple Python 3 program to add two matrices. To understand this program, you should know the following basic concepts of Python programming language:

• Lists
• For and nested for loops

## Python 3 Program To Add Two Matrices

We will use Python lists to store our matrices. We will cover lists in detail later, but let’s understand it from a top-level view for now. A Python list is an array, but it can store homogeneous datatypes. For example, you can store strings, numbers, bool, or any combination of these data types in a list.

In other words, the list is a collection of ordered and changeable data. Lists also support duplicate items.

Syntax of declaring Lists:

`myFriends = ["Himanshu", "Abhishek", "Vivek", 1, 2, 3]`

The following list myFriends now stores string values and integer values.

Likewise, you can also store multiple lists inside a list. Using this feature of Python lists, we can store our matrices.

To store a matrix of 3 by 3, we can create a list and define three lists with numbers, as shown in the diagram below.

Therefore, to add two matrices, we must create two lists (with three sub-lists of 3 numbers) and add them together. Please refer to the diagram below for a better understanding of the concept.

To iterate through these lists, we can use for loops, add each number to its corresponding number in the second list, and store the result in a third list.

### Source Code

```a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
b = [[9, 8, 7],
[6, 5, 4],
[3, 2, 1]]
sum = [[0, 0, 0],
[0, 0, 0],
[0, 0, 0]]
for i in range(len(a)):
for j in range(len(a[0])):
sum[i][j] = a[i][j] + b[i][j]

for i in sum:
print(i)```

[10, 10, 10]

[10, 10, 10]

[10, 10, 10]

### Wrapping Up

In this tutorial, you learn how to add two matrices. Stay tuned for more Python 3 programs working with matrices such as multiplication, subtraction, etc.

Let me know if there are any tutorials or concepts you would like us to cover in our future posts.

Enjoy Python learning :)

### Related Python Programs:

Himanshu Tyagi
Hello Friends! I am Himanshu, a hobbyist programmer, tech enthusiast, and digital content creator. Founder Cool SaaS Hunter. With CodeItBro, my mission is to promote coding and help people from non-tech backgrounds to learn this modern-age skill!
RELATED ARTICLES