0

I have a 2D matrix in a block of Python3 code the output of which looks like this:

[
 [0, 0, 0, 0],
 [0, 0, 0, 0]
]

the code that initializes this is simply like this:

mat = [[0] * col] * row

where, col = 2, row = 4

now, there's a loop which is supposed to update the value based on the index:

for i in range(len(mat)):
    for j in range(len(mat[0])):
        if i == 0:
            print(i, j)
            mat[i][j] = 999 

print(mat)

It prints out:

0 0
0 1
0 2
0 3
[[999, 999, 999, 999], [999, 999, 999, 999]]

Which doesn't seem the logical output since I am updating only on the indices when i = 0

Moreover, if the code for initialization is altered to:

mat = [
 [0, 0, 0, 0],
 [0, 0, 0, 0]
]

instead of:

mat = [[0] * col] * row

then the output is as expected:

[[999, 999, 999, 999], [0, 0, 0, 0]]

What is the reason behind this inconsistency of output depending on the initialization of the matrix? Also, how did all the indices in the first output (unexpected one) got updated to 999 where it was explicitly checked with the i == 0 and the logs also verify that?

Abrar
  • 5,956
  • 8
  • 26
  • 38

0 Answers0