"is" and "=="

Thomas Wouters thomas at xs4all.net
Tue Mar 11 18:24:43 CET 2003


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 *' :)

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!





More information about the Python-list mailing list