+ 1

Python challenge question

I got this question in a Python Challenge. Answer is [1,[2,5]] a =[1,[2,3]] b=a[:] a[0]=3 a[1][1]=5 print(b) So what does [:] do, and why is 5 added into b but 3 is not added?

13th Feb 2022, 5:19 PM
Wolfneck
Wolfneck - avatar
4 ответов
+ 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.
13th Feb 2022, 5:25 PM
Per Bratthammar
Per Bratthammar - avatar
+ 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.
13th Feb 2022, 5:43 PM
Per Bratthammar
Per Bratthammar - avatar
+ 1
Ah thanks Per! I understand now
14th Feb 2022, 12:05 AM
Wolfneck
Wolfneck - avatar
0
Hi Per! So in that case, why does a[1][1] replaces the number with 5 in b as well?
13th Feb 2022, 5:27 PM
Wolfneck
Wolfneck - avatar