Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python different results of code [duplicate]

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]
like image 956
user3400748 Avatar asked Mar 23 '26 04:03

user3400748


1 Answers

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

like image 100
itzMEonTV Avatar answered Mar 25 '26 19:03

itzMEonTV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!