"is" and "=="
Dagur Páll Ammendrup
dagurp at heimsnet.is
Tue Mar 11 12:32:53 EST 2003
Thomas Wouters wrote:
>On Tue, Mar 11, 2003 at 04:46:26PM +0000, Dagur Páll Ammendrup wrote:
>
>
>>I was wondering when == should be used and when "is". I like using "is"
>>when comparing strings and stuff but maybe I shouldn't?
>>
>>
>
>Yes, you shouldn't. 'is' tests for identity; whether you have two references
>to the same object. This often looks the same as testing for equality when
>doing small tests with small immutable objects (like small integers or short
>strings) in the interactive interpreter, but easily breaks for real-world
>comparisons:
>
>
>
>>>>"spam" is "spam"
>>>>
>>>>
>1
>
>
>>>>"spam" is "sp" + "am"
>>>>
>>>>
>0
>
>
>>>>101 is 101
>>>>
>>>>
>1
>
>
>>>>101 is 100 + 1
>>>>
>>>>
>0
>
>The 'id' function might make it clearer for you:
>
>
>
>>>>id("spam"), id("spam")
>>>>
>>>>
>(135743896, 135743896)
>
>
>>>>id("spam"), id("sp" + "am")
>>>>
>>>>
>(135743896, 135743944)
>
>
>>>>id(101), id(100 + 1)
>>>>
>>>>
>(135388108, 135388048)
>
>The reason the 'is' test succeeds so often for simple tests is because
>Python caches strings (in particular ones created from string-literals, like
>"spam" and "sp" above) and small numbers internally, which is safe to do
>since they are immutable. You should not rely on this behaviour, though.
>
>There are very few uses of 'is' in normal user code...
>(much like 'from module import *' :)
>
>
>
Ah ok, I wish it was the same as ==, it just looks nicer :-)
More information about the Python-list
mailing list