4 Answers
+ 5
Hi! Lists are mutable objects. When you use b=a[:], itâs the same as use b=a.copy(); you create a copy of a.
+ 1
# Hi! You can try test these two:
import copy
a = [1, [2, 3]]
b = copy.deepcopy(a)
a[0] = 3
a[1][1] = 5
print("deepcopy:", b)
del a, b
a =[1, [2, 3]]
b = copy.copy(a)
a[0] = 3
a[1][1] = 5
print("copy:", b)
# When you use a[:] or a.copy() there will be only a shallow copy of a. But in a = [1, [2, 3]] there is a list [2, 3]. This will not be copied with a[:]. To copy even âon the deepâ, you import copy and use b = copy.deepcopy(a). Then the objects in b no longer will be change, when you change the values in a.
+ 1
Ah thanks Per! I understand now
0
Hi Per! So in that case, why does a[1][1] replaces the number with 5 in b as well?