Result of ``a is b''

David MacQuigg dmq at gain.com
Mon Mar 15 23:17:52 EST 2004


On 15 Mar 2004 16:32:25 -0800, axelboldt at yahoo.com (Axel Boldt) wrote:

>is there a rationale for the following behavior:
>
>  >>> a = (1,2)
>  >>> b = (1,2)
>  >>> a is b
>  False
>  >>> a = "12"
>  >>> b = "12"
>  >>> a is b
>  True

Here's another one:
>>> x = 'akdijfkdienlskfi'
>>> y = 'akdijfkdienlskfi'
>>> x is y
True
>>> x = 'a b'
>>> y = 'a b'
>>> x is y
False
>>> x == y
True
>>> 

It has to do with how Python decides which strings to "internalize"
and make shared objects in order to save space.  This is only a
problem with immutable objects.  Others cannot be shared like this.

My suggestion is to *never* use 'is' with these objects unless you
really need the fact that it is faster than '==' and you test it
thoroughly for the kind of objects you will be comparing.

-- Dave




More information about the Python-list mailing list