I was trying to create a list matrix in python in a easy way but turns out it was wrong (method 1), instead of copy the list rows, it actually just copy the list address. Can anyone shed some light to explain this in-depth? What I trying to achieve is method 2, but I don't understand why method 1 don't work.
Thanks,
# method 1
res=[[None]*4]*4
res[1][0]=-1
print(id(res[0]))
print(id(res[1]))
print(id(res[2]))
print(id(res[3]))
# output 1
140475957049792
140475957049792
140475957049792
140475957049792
# method 2
res=[[None for j in range(4)] for i in range(4)]
res[1][0]=-1
print(id(res[0]))
print(id(res[1]))
print(id(res[2]))
print(id(res[3]))
# output 2
140475957617344
140475957617280
140475957617216
140475957617152
CodePudding user response:
Becouse your first code make python-object [None]*4
and duplicate link to this object 4 times. It is not deep copy.
Second code 4 times make other objects those makes with list comprehension. It is not copy.
CodePudding user response:
Hopefully I can answer this question in a manner which is clear to you. Let's start with the first example where you invoke res=[[None]*4]*4
. In this example you are taking the list object [None] 4 times. and forming a outer list [[None],[None], [None], [None]] and making 4 copies of this list. When you print the id of these four lists, they point to the same object id.
In your second example, you are using list comprehension to make new objects for each sequence and therefore you get different id's for each list.
You can demonstrate for yourself these differences if make a change to 1 cell such as res[1][1] = 1 and then print res.