+ 4
Could Someone explain this code please
What is the output of this code? a = [1, [2, 3]] b = a[:] a[0] = 3 a[1][1] = 5 print(b) The answer is [1, [2, 5]]!! but how?? Thanks
7 Réponses
+ 14
Lists are tricky, indeed... ;)
b gets assigned anew with values of a. So it's now [1, [2, 3]]. Mind, that it actually means that the first element being an integer, gets copied, but the second element, which is a list [2, 3] gets *referenced* to.
Then a[0] is changed, which does not influence b.
*But* when a[1][1] is changed, it changes the value in the memory location which b[1] references to.
This is why when a[1][1] is assigned to 5, both a[1] and b[1] point to [2, 5].
So b is now [1, [2, 5]]
+ 4
# If you want the output to be [1, [2, 3]] use this code
from copy import deepcopy
a = [1, [2, 3]]
b = deepcopy(a)
a[0] = 3
a[1][1] = 5
print(b)
+ 3
@Kuba, Thank you!
I didn't know this property of list but now it makes sense :)
+ 2
Ingrid No problem. Kindly please mark my answer as best (✔️ on the left) if it helped you, keeps my motivation up ;)
+ 1
Is a[:] equal to copy(a) or why does the integer get copied? I remember learn that lists are always passed by reference.
+ 1
Tricky lists :)
+ 1
There are different ways to copy a list, but some of them only create a shallow copy so it is modified when the original is modified https://code.sololearn.com/cV5e805UQ43A/?ref=app