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?

5th Oct 2020, 3:19 AM
Solus
Solus - avatar
4 Respostas
+ 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)
5th Oct 2020, 3:39 AM
Ruba Kh
Ruba Kh - avatar
+ 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.
5th Oct 2020, 9:38 PM
Solus
Solus - avatar
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
5th Oct 2020, 9:33 PM
Solus
Solus - avatar
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 👍🏼
5th Oct 2020, 9:43 PM
Ruba Kh
Ruba Kh - avatar