Fundamental question about assignment in Python. Can somebody help out? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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?

8th Apr 2020, 7:26 PM
Felix Lipo
Felix Lipo - avatar
4 Answers
+ 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
8th Apr 2020, 7:37 PM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 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
8th Apr 2020, 7:46 PM
HonFu
HonFu - avatar
+ 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
8th Apr 2020, 7:47 PM
Bahhaⵣ
Bahhaⵣ - avatar
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)
9th Apr 2020, 5:43 PM
Felix Lipo
Felix Lipo - avatar