0

Why b[0] = 1 and not 3?

a = [1, [2, 3]] b = a[:] a[0] = 3 a[1][1] = 5 print(b)

19th May 2020, 1:09 PM
Gleboffsky
Gleboffsky - avatar
3 Answers
+ 4
when you copy like this [:] if creates another reference in the memory. if you do a = [1,2] , b = a then a == b and a is b. but when you create it like this b = a[:] then a == b and a is not b and b is [1, [2,5]] because of the shallow copy. which means that when you use this technique like a = b, it copies only first level of list of memory to a new reference. if you have list in list, the second list is not copied but based in the reference of the copied element if you do this: a=[1, [2,3]] b=a a [0]=3 a [1][1]=5 then b = [3, [2,5]] there is also another trick to it which helps you avoid shallow copy by doing this: from copy import deepcopy a=[1, [2,3]] b=deepcopy(a) a [0]=3 a [1][1]=5 then b = [1, [2,3]]
19th May 2020, 1:16 PM
Sebastian Pacurar
Sebastian Pacurar - avatar
+ 3
Gleboffsky, the tags are meant to help other users find your question if they have a similar problem. Try to find something related to your question.
19th May 2020, 3:14 PM
HonFu
HonFu - avatar