Skip to content

Instantly share code, notes, and snippets.

@ShyamaSankar
Created March 17, 2019 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ShyamaSankar/af33dc67c8967a836bdbdaba05ec1b4f to your computer and use it in GitHub Desktop.
Save ShyamaSankar/af33dc67c8967a836bdbdaba05ec1b4f to your computer and use it in GitHub Desktop.
Matrix addition using nested list comprehension and nested for loops.
# 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