English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to add two matrices using nested loops and list comprehension, and display them.
To understand this example, you should understand the followingPython programmingTopic:
In Python, we can implement a matrix as a nested list (a list within a list). We can consider each element as a row in the matrix.
For example, X = [[1, 2], [4, 5], [3, 6]] will represent a3x2Matrix. The first row can be X[0], and the element in the first row and first column can be X[0][0].
We can perform matrix addition in various ways in Python. Here are some examples.
# Program to add two matrices using nested loops X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] result = [[0,0,0], [0,0,0], [0,0,0]] # Traverse 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)
Output result
[17, 15, 4] [10, 12, 9] [11, 13, 18]
In this program, we use nested for loops to traverse each row and column. At each point, we add the corresponding elements from the two matrices and store them in the result.
# Program to add two matrices using list comprehension X = [[12,7,3], [4 ,5,6], [7 ,8,9]] Y = [[5,8,1], [6,7,3], [4,5,9]] result = [[X[i][j] + Y[i][j] for j in range(len(X[0])) for i in range(len(X))] for r in result: print(r)
The output of the program is the same as the one above. We use nested list comprehension to traverse each element in the matrix.
List comprehension allows us to write concise code. We must try to use them frequently in Python. They are very helpful.