That might be the case for more complex objects...

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Sat Apr 14 21:30:21 EDT 2007


On Sat, 14 Apr 2007 16:03:03 -0400, Bart Willems wrote:


> I can try this in interactive mode:
>  >>> a = 5
>  >>> b = a
>  >>> a += 1
>  >>> print b
> 5
> 
> So, if /a/ and /b/ where pointing to the *same* "5" in memory, then I 
> would expect b to be increased, just as a.

This is what you are implicitly _thinking_:

"a" points to a memory location, holding a few bytes with the bit pattern
0x05. When I add 1 to it, the bytes change to 0x06.

But integers in Python aren't bit patterns, they are objects. You can't
make the 5 object have value 6, that would be terrible:

py> 5 + 5  # remember that 5 has been changed to have value six!
12

So a += 1 rebinds the name "a" to the object 6. The name "b" still points
to the object 5, because you didn't do anything to "b".

Now, for extra credit: can you explain why this happens?

>>> alist = [0]
>>> blist = alist
>>> alist += [1]
>>> blist
[0, 1]



-- 
Steven.




More information about the Python-list mailing list