Python's Reference And Internal Model Of Computing Languages

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Fri Feb 5 17:26:03 EST 2010


On Fri, 05 Feb 2010 09:53:33 -0600, David Thole wrote:

> I read this....and am a tiny bit confused about the actual problem.
> 
> It's not exactly complex to realize that something like: a = b = array
> that a and b both point to the array.
> 
> Logically speaking, I'm not sure how one could assume that the same
> assignment would yield a and b point to the same duplicate array.

It's an easy mistake to make, if you don't understand Python's object 
model:


>>> a = b = 2
>>> a += 1
>>> a, b
(3, 2)
>>> a = b = [2]
>>> a[0] += 1
>>> a, b
([3], [3])

For the non-Python coders reading, the difference is that ints are 
immutable, and hence a += 1 assigns a to a new int, leaving b untouched, 
but lists are mutable, hence a[0] += 1 mutates the list which both a and 
b refer to. This is a Good Thing, but it is one of the things which give 
newcomers some trouble.


-- 
Steven



More information about the Python-list mailing list