0

Python list operation

a = [1,[2,3]] b = a[:] a[0] = 3 a[1][1]= 5 print (b) #Outputs [1,[2,5]] Why a[0] = 3 doesn't get executed?? Why it doesn't output [3,[2,5]]

4th Jan 2021, 5:53 AM
CHANDAN ROY
CHANDAN ROY - avatar
2 odpowiedzi
+ 7
b = a[:] makes <b> becoming a shallow copy of <a>. In shallow copy, object reference is copied in case of mutable objects (such as a `list`). Contrary, object value is copied in case of immutable object (such as an `int`). So for the object <b> here, it contains two objects. One `int` object (immutable) at index 0, and one `list` object (mutable) at index 1. So why the `int` object at b[0] isn't affected by the command `a[0] = 3`? it's because `int` object at b[0] is an object with no connection to the `int` object at a[0]. It is a mere copy of value, not reference. But why the `list` object at b[1] is affected by the command `a[1][1] = 5`? it's because `list` object at b[1] is a reference copy that points to the same `list` object at a[1]. So modifying either a[1] or b[1] will reflect the changes to both <a> and <b>. Hope it made some sense : )
4th Jan 2021, 6:48 AM
Ipang
+ 5
Okay so this might sound a bit complicated at first, but it is really simple. You might know that lists are reference types, i.e., they are passed by reference, for example a = 2 b = a a = 1 here b will still be 2, even though we changed a to 1 But here a = [1, 2, 3] b = a a[0] = 0 here the value of `b` will also change. Now in your code, if the line `b = a[:]` was changed to `b = a`, then the output would be [3, [2, 5]], but doing `a[:]` *copies* the list and makes a new list which is independant of `a`. That is why when `a[0] = 3` is done, b[0] is not changed. Now you may ask why `a[1][1] = 5` changes b[1][1]. This is because doing `a[:]` only copies `a`, not the elements of `a`. The elements of `a` which are reference types like list, are only copied as references to the original value inside `a`. That is why b[1][1] changes when a[1][1] is changed
4th Jan 2021, 6:54 AM
XXX
XXX - avatar