0
Python - If b = a[:], how come a[1][0] = 555 modifies b while a[0] = 3 does not?
a = [1,[2,3]] b = a[:] # b = [1,[2,3]] a[0] = 3 print(a) # outputs [3, [2, 3]] print(b) # outputs [1, [2, 3]] --> b didn't change a[1][0] = 555 print(a) # outputs [3, [555, 3]] print(b) # outputs [1, [555, 3]] --> b changed Why did a[1][0] = 555 change b while a[0] = 3 did not?
4 Respuestas
+ 4
So there is different types of copy first lets talk about assignment in assignment if you make
b =a any change in b will also change a because b is not copy of a instead a reference.
Then there is deep and shallow copy,
in this case it is a shallow copy which means the list is copied to a new one however its children still a reference to the original one. So if you modify in the new outer list it will not affect the original but if you modify in new inner list the original inner list will also change because the new inner list is just a reference to the old one. There is another way to do shallow copy which is to import copy then do
b = copy.copy(a).
If you want to make a deepcopy which will completley create anew object for the list and the children and any changes in b will not affect a you have to import copy then use
b = copy.deepcopy(a)
+ 1
Ruba Kh
However, I'm NOT making any changes to the new outer or new inner list.
I'm assuming that the concepts of shallow/deep copy still applies even if we are
modifying the ORIGINAL.
I'm treating the original list (ie. a) as a copy...
From my understanding, the original list and a variable that is assigned to this list
are COPIES OF EACH OTHER.
Please correct me if I'm wrong.
0
Shallow copy: changes to copy DO AFFECT original
--> only nested list(s) / inner list(s) are reference(s)
--> outer list is treated like a deep copy
Deep copy: changes to copy do NOT affect original
0
Yeah you are absolutely right any changes in any one of them will be affected on the other on the conditions I mentioned, since they refrence the same memory location so it is basically the same 👍🏼