Created
March 17, 2019 09:45
-
-
Save ShyamaSankar/af33dc67c8967a836bdbdaba05ec1b4f to your computer and use it in GitHub Desktop.
Matrix addition using nested list comprehension and nested for loops.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Our list of lists. | |
matrix_1 = [[1,1,1], [2,2,2], [3,3,3]] | |
matrix_2 = [[4,4,4], [5,5,5], [6,6,6]] | |
# Matrix addition with for loop. | |
# Assuming that the matrices are of the same dimensions | |
matrix_sum = [] | |
for row in range(len(matrix_1)): | |
matrix_sum.append([]) | |
for column in range(len(matrix[0])): | |
matrix_sum[row].append(matrix_1[row][column] + matrix_2[row][column]) | |
# Rewrite using list comprehension only for inner lists. | |
matrix_sum = [] | |
for row in range(len(matrix_1)): | |
matrix_sum.append([matrix_1[row][column] + matrix_2[row][column] for column in range(len(matrix[0]))]) | |
# Rewrite using nested list comprehension. | |
matrix_sum = [[matrix_1[row][column] + matrix_2[row][column] for column in range(len(matrix[0]))] | |
for row in range(len(matrix_1))] | |
print(matrix_sum) # Output: [[5, 5, 5], [7, 7, 7], [9, 9, 9]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment