I want to understand the difference between the following two ways of initializing a 2-dim list in python:
r1=2
c2=2
result = [[0] * r1] * c2
This makes a 2x2 list initialized with all zeros
and when I write:
result = [[0,0],[0,0]]
This also creates a 2-dim list initialized with zeros (is this true?)
Now when I insert values in the first case, like this:
r1=2
c2=2
result = [[0] * r1] * c2
for i in range(r1):
for j in range(c2):
result[i][j] = i+j
print()
print(result)
This does not insert the correct values, and rather the same values are repeated in both rows
However, when I insert values like this, in the second case:
r1=2
c2=2
result = [[0,0],[0,0]]
for i in range(r1):
for j in range(c2):
result[i][j] = i+j
print()
print(result)
This inserts the correct values.
What is the reason of wrong values insert in the former case and correct values in the latter case?
Thanks.