2 views
in Python
edited

I want to generate a simple method that will yield the sum of two matrices (nested lists). I do not know why the code below does not work as expected.

Code:

matrix_a = [[1, 2, 4], [0, 1, 3], [2, 2, 8]]

matrix_b = [[0, 3, 1], [5, 4, 2], [8, 2, 6]]

rows = len(matrix_a)

columns = len(matrix_a[0])

result = [[0] * columns] * rows

for x in range(rows):

for y in range(columns):

result[x][y] = matrix_a[x][y] + matrix_b[x][y]

print(f'[{x}][{y}]: {matrix_a[x][y]} + {matrix_b[x][y]} = {result[x][y]}')

print(result)

Output:

[0][0]: 1 + 0 = 1

[0][1]: 2 + 3 = 5

[0][2]: 4 + 1 = 5

[1][0]: 0 + 5 = 5

[1][1]: 1 + 4 = 5

[1][2]: 3 + 2 = 5

[2][0]: 2 + 8 = 10

[2][1]: 2 + 2 = 4

[2][2]: 8 + 6 = 14

[[10, 4, 14], [10, 4, 14], [10, 4, 14]]

Why the last record is copied three times?

by (108k points)

When you are executing [[0] * columns] * rows you're basically generating a list of 3 references to the same list.

It is equivalent to the following code:

a = [0, 0, 0]      # a = [0] * columns

result = [a, a, a] # result = [a] * rows

Therefore when you do result[0], result[1] and result[2] you're actually referencing the same underlying memory as a. Since they all are referencing to the same object, when you do the last three lines:

[2][0]: 2 + 8 = 10

[2][1]: 2 + 2 = 4

[2][2]: 8 + 6 = 14

You're basically modifying the same underlying entity, a (in our case). If you want to allow the result array programmatically, then you'll have to do

result = [[0] * columns for _ in range(rows)]

Interested in learning Python? Enroll in our Python Course now!