[Tutor] Identity operator (basic types)

Daniel Yoo dyoo at cs.wpi.edu
Sat Feb 10 06:57:26 CET 2007



>> Why does the identity operator return "True" in the below cases,
>> that is when assigning  the same value to basic variable types
>> (float, integer, string, bool..)? Are these rcopied by reference
>> (shallow)? If so why?
>>
>>>>> i = 10
>>>>> j = 10
>>>>> i is j
>> True

The above you have here is not guaranteed behavior --- in fact, in the 
general case, you won't see this.  The thing is that numbers that are 
"small" (< 100) are cached in Python as a low-level optimization, so every 
time you say '10', you get the same value.


> Here you're saying that "i" is equal to 10 and that "j" is equal to 10. 
> Therefore "I' and "j" are the same

That may be "equal", but there is no guarantee that they will be 
identical.  Concretely:

################
>>> x = 1234567
>>> y = 1234567
>>> x is y
False
################



>>>>> a = 10
>>>>> b = a
>>>>> a is b
>> True

This, on the other hand, guarantees that 'is' will return true: the two 
names 'a' and 'b' refer to the same object.



I think we should be careful about using the word "equal" and "same", so 
let me make sure we agree on terms.

     a == b   "a's value equals b's value."

     a is b   "a and b refer to the same value."


More information about the Tutor mailing list