"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

>>> "spam" is "spam"
>>> "spam" is "sp" + "am"
>>> 101 is 101
>>> 101 is 100 + 1                                                              

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