[Tutor] Object comparison vs. Identity

Sheila King sheila@thinkspot.net
Sun, 11 Mar 2001 09:41:59 -0800


Thanks, Danny, for the explanation about the list of cached ints. I think I
will e-mail this thread to the author, so that he is aware that this example
from his book needs to be changed. Or at least, he should modify SOMETHING
with respect to using certain integers to show the difference in object
identity.

--
Sheila King
http://www.thinkspot.net/sheila/
http://www.k12groups.org/


On Sat, 10 Mar 2001 22:36:52 -0800 (PST), Danny Yoo
<dyoo@hkn.eecs.berkeley.edu>  wrote about Re: [Tutor] Object comparison vs.
Identity:

:On Sat, 10 Mar 2001, Sheila King wrote:
:
:> On pp. 84 - 85 he is discussing object identity, and presents the following
:> example:
:> foo1 = 4
:> foo2 = 3 + 1
:> He says that the first statement creates a numeric object and assigns it to
:> foo1. The second statement creates a numeric object, and assigns it to foo2.
:> Although the value of the two objects are the same, he claims that they are
:> two distinct objects. 
:> (I read this as implying, that while 
:> foo1==foo2 would return 1, 
:> he is saying that id(foo1) == id(foo2), 
:> or alternatively foo1 is foo2
:> would both return 0.)
:
:
:True; however, the reason that this doesn't work for small numbers is
:because the integers are precached --- Python keeps instances of the
:integers from -1 to 100 to reduce the cost of using these popular numbers.  
:We can empirically see this with a small experiment:
:
:###
:>>> for i in range(-1, 105):
:...     x = int(i * 1.0)        ## Doing a little bit of trickery here
:...     y = int(i * 1.0)        ## to guarantee the construction
:...     if x is not y: print x
:... 
:100
:101
:102
:103
:104
:###
: