+ 2
Fundamental question about assignment in Python. Can somebody help out?
The following issue confuses me alot. This code is from a Challenge question: a = [1,2,3,4,5] b = a b[4] = 0 print (a[4]) The correct answer is 0. When I insert the code into a console I get 0 as well. BUT: I was sure the answer would be 5 because I thought that the list 'a' remained untouched. In my mind, in line 2 the variable 'b' is created, the properties of 'a' are assigned to it and that's it. Apparently this is not true. Could somebody explain what is actually going on?
4 ответов
+ 5
Felix Lipo , I think the reason is that both lists refer to the same object. You could check it with id function which gives the same address. So when you make a change in the second list you make changes also in the first one. For further information look at the code 🐱
https://code.sololearn.com/cV2gzhC6eTku/?ref=app
+ 4
If you care to take a close look at the issue (I promise you, it will come up very often), you could take a look into this tutorial I made.
https://code.sololearn.com/c89ejW97QsTN/?ref=app
+ 3
as mentioned above only the reference of (a) is passed to (b).
it didn't create a new list (b).
then there's list index that starts from 0.
b[4] = 0 overwrites 5 and becomes 0
0
Hey guys, thanks alot for the good answers! And nice tutorial, Honfu! It's cool that it explains how lists are MUTABLE (unlike ints). Seems like references work a bit like horcruxes in Harry Potter - you have to remove them all to remove the actual object ;)
I found another Q&A where someone listed ways to go around this:
https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list
So in my case line 2 could have been the following to create to seperate objects:
b = list(a)