Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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]]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement