3

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]
Remi Guan
  • 21,506
  • 17
  • 64
  • 87

2 Answers2

4

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

itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
3

The value of the two objects in question differs, one, the int is immutable while the other, the list is mutable.

By assigning both names x, y to 5 you create two different names for the same value 5. When you perform an operation:

In [1]: x = y = 5

In [2]: x = x + 1

In [3]: x
Out[3]: 6

In [4]: y
Out[4]: 5

x+1 returns a new int object because you cannot change the value of an int.

list types on the other hand are mutable. So when you create two names that reference the same list and then change the value of its contents with assignment via x[0] = 1 it simply affects the list being referenced by x and doesn't create a new list. So, results of this assignment are visible to y too because they reference the same mutable object:

In [11]: x = y = [5]

In [12]: x[0] = 1

In [13]: x
Out[13]: [1]

In [14]: y
Out[14]: [1]

Note that adding x = x + [1] will create a new list, what you are doing with x[0]=1 is simply changing the contents. Take a look at this presentation for a more complete coverage.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253