+ 1
Help me explain this code plz.Why i change a[0]=3 but b is equal [1,[2,5]] but i change again a[1][1]=4 and now b =[1[2,4]]????
a=[1,[2,5]] b=a[:] a[0]=3 a[1][1]=4 print(b)
3 odpowiedzi
+ 4
https://docs.python.org/3/library/copy.html
+ 3
because b = a[:] create a shallow copy of a... meaning that list stored at a[1] is the same object as b[1] (copy by reference)
+ 1
cause u copy
when u use [:] to create b, now u have new list that have same value as a
but only the outer one
so changing a[0] wont affect b[0], but a[1][1] still point to same list as b[1][1]
if u want b[1][1] to point to differ list, than u can do b[1]=a[1][:]