#First
x = 9
y = x
x = 18
print(y)
#Second
S = {1,3,4,5,6}
T = S
T.remove(5)
print(S)
First : The result is 9
Second : The result is {1,3,4,6}
At the first, the y is not changed by x's change. At the second, the S is changed by T's change. I wanna know the reason. Thank you in advance! =)
-
Reut is correct. If you want to demonstrate the difference between mutable and immutable objects, you need to modify x rather than completely reassign it. Your comment hints that you understand this, so what is your question?BlivetWidget– BlivetWidget2015年10月05日 03:04:52 +00:00Commented Oct 5, 2015 at 3:04
2 Answers 2
This is a very common question. For Python, it's helpful to read this section of the language reference.
In short, in Python, you have names bound to objects.
In your first example you bind to the name x the object whose value is the integer 9. Then you bind to y that same object. Next you bind to x the object whose value is the integer 18. The object bound to y is still the one with the value 9, so 9 is printed.
In your second example, you bind a set object to S. Then you bind that same object to T. The code T.remove(5) mutates the object bound to T, which is the same object bound to S. That is why when you inspect S, you see the change that made through T, because the names S and T were bound to exactly the same object.
In pictures:
x = 9
x -----------> 9
y = x
x -----------> 9
^
|
y -------------+
x = 18
x -----------> 18
y ------------> 9
See y did not change. Why not? Because I bound x to a new object. But I did not change what y was bound to. Now let's look at the second example
S = {1, 3, 4, 5, 6}
S -----------> 1 3 4 5 6
T = S
S -----------> 1 3 4 5 6
^
|
T -------------+
T.remove(5)
S -----------> 1 3 4 6
^
|
T -------------+
The object bound to S changes. Note I did not say that S changed! I never changed the bindings; S and T still point to the same object. It is very important to understand the difference between the names and the objects bound to them.
Also note, I did not say the word "variable." :)
Comments
you start with x as an reference to object with the value 9, then y as a reference to the same object as x. after you assign x to a new object with the value 18, x now refers to a different object but y still refers to the same object with the value 9.