confused about Python assignment

Peter Hansen peter at engcorp.com
Thu Oct 30 22:22:17 EST 2003


Stephen Horne wrote:
> 
[snip]
> This assignment is *ALWAYS* by reference, including with integers, but
> with immutable values such as integers the by-reference thing isn't so
> obvious.
> 
> It is hard to make this clear with integers (at least for simple
> examples, there seems only ever to be one object with the value '1'
> for instance) but it can be made obvious with floats, which are also
> immutable...

It's equally "obvious" with integers, if you pick values above 99 or
below -5 (found by experimentation this time, as my memory is always
poor, and using Python 2.3.1).

Try 

a = 99
b = 99
a is b  (returns True)

a = 100
b = 100
a is b  (returns False)

Values between -5 and 99 inclusive are basically pre-created and
"interned" so that you never get multiple integer instances with the
same values in this range.  Those outside this range are not treated
specially like this.

-Peter




More information about the Python-list mailing list