I'm just beginning to learn and read about Python and have question that I'm having trouble understanding while reading the first few chapters of the book. I came across this while playing around with the interpreter.
Here is my question, how come the values differ in both of these expressions. In the first example, the value of y remains the same after changing x, while in the next example when changing x, it also changes the value of y.
Example 1:
>>> x = 5
>>> y = x
>>> x += 1
>>> x
6
>>> y
5
Example: 2
>>> x = [5]
>>> y = x
>>> x[0] = 6
>>> x
[6]
>>> y
[6]
Its about python reference.When
a = [2]
b = a
Here a, and b both referencing to [2].You can check it by id
>>>id(a)
3066750252L
>>>id(b)
3066750252L
Both are same ids. So a.append or b.append will affect both a and b.That is [2].This is in case of mutable objects.So a[0]=6 will affect b also.In case of integers, it will not affect since, int is immutable object.So
>>>a = 2
>>>id(a)
164911268
>>>a = a + 1
>>>a
3
>>>id(a)
164911256
Here id changed.That means new int object is created 3.It is now referencing by variable a.
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With