Explanation of list reference

Ian Kelly ian.g.kelly at gmail.com
Fri Feb 14 15:12:51 EST 2014


On Fri, Feb 14, 2014 at 11:54 AM, dave em <daveandem2000 at gmail.com> wrote:
> Thanks for your quick response.  I'm still not sure we understand.  The code below illustrates the concept we are trying to understand.
>
> Case 1: Example of variable with a specific value from P 170 of IYOCGWP
>
>>>> spam = 42
>>>> cheese = spam
>>>> spam = 100
>>>> spam
> 100
>>>> cheese
> 42
>
> Case 2: Example of variable with a list reference from p 170
>
>>>> spam = [0, 1, 2, 3, 4, 5]
>>>> cheese = spam
>>>> cheese[1] = 'Hello!'
>>>> spam
> [0, 'Hello!', 2, 3, 4, 5]
>>>> cheese
> [0, 'Hello!', 2, 3, 4, 5]
>
> What I am trying to explain is this, why in case 1 when acting on spam (changing the value from 42 to 100) only affects spam and not cheese.  Meanwhile, in case two acting on cheese also affects spam.

In the first case, after the assignment "cheese = spam", the names
spam and cheese are bound to the same object (42).  If you were to
modify the object 42 (which you cannot do in this case, because ints
are immutable) then you would see the change reflected in the object
regardless of which name you used to access it.  You then rebind the
name "spam" to a different object (100), which does not affect the
binding of the name "cheese" at all; the names end up referring to
different objects.

In the second case, after the assignment "cheese = spam", the names
again are bound to the same object, a list.  The assignment "cheese[1]
= 'Hello!'" then *modifies* that list, without rebinding cheese.
cheese and spam continue to refer to the same object, and since it was
modified you can see the change in that object regardless of which
name you used to access it.

If in the second case, you were to explicitly copy the list (e.g.
"cheese = list(spam)") prior to modifying it, then the two names would
instead be bound to different objects, and so subsequently modifying
one would not affect the other.

So the short answer is that there is no difference at all between the
way that names are bound to ints and the way they are bound to lists.
There only superficially appears to be a difference because ints are
immutable and lists are not.



More information about the Python-list mailing list