Python Encapsulation Question
Hi there, I've got some experience with writing Java and have decided to attempt to pick up Python via Automatetheboringstuff (which is pretty good I must say).
So in chapter 8 (reading and writing files) there is an exercise to generate a bunch quizzes with randomized order of answers. I'm trying to write my own implementation before comparing it to the given answers. However I've stumbled upon a concept in python that has confused me.
My code is at https://pastebin.com/6sEMMKeT
For some reason, when I iterate through the list of states and remove the correct answer, it seems to remove the capital for the global variable as well. I assumed that when I linked the global variable to a local variable in a for loop, the global should not be affected. But here, I'm seeing a decrease even in the global variable.
Is this normal behaviour or have I missed a major concept in programming?
6 comments · 100% upvoted · other discussions
When you assign variable
ato another variableb, bothaandbare pointing to the same object in memory. Lists are also mutable so if you modify the list using either variable, both will be pointing to that modified list (which is what you see in your example).You can get around this by copying the list
EndUsersarePITA [OP] 1 points · Oct 2019
Thank you for the example. You are absolutely right. But this doesn't apply to variables though.
For example :
vervain9 1 points · Oct 2019
In your original example you have two variables pointing at the same list and you then modify the underlying list that both variables point to using
random.shuffle(which changes the order of items in a list without creating a new list).In this case you're re-assigning
xto 2, which is a completely new object, and will not affecty.xandyare not linked, they were just both pointing to the same object originally (the int 1). Once you dox = 2, you're makingxpoint to something else.