Equality and identity

Asun Friere afriere at yahoo.co.uk
Wed Mar 31 01:47:31 EST 2004


Marius Bernklev <mariube+netnews+ at ifi.uio.no> wrote in message news:<3cfvfkmi337.fsf at nelja.ifi.uio.no>...
> In python, it seems like immutable objects are equal under both
> equality and identity:
> 
> >>> 5 == 5
>  True
> >>> 5 is 5
>  True
> >>> "hei" == "hei"
>  True
> >>> "hei" is "hei"
> True
> 

It only seems that way.  Note:
>>> a = 5
>>> b = 5
>>> 100 is 100
True
>>> #but:
>>> a = 100
>>> b = 100
>>> a is b
False
>>> #but also!:
>>> a = 100;b = 100
>>> a is b
True
>>> # for strings:
>>> a = 'hello'
>>> b = 'hello'
>>> a is b
True
>>> a = 'hello world'
>>> b = 'hello world'
>>> a is b
False
>>> a = 'hello world';b = 'hello world'
>>> a is b
True

As was pointed out, this is implementation dependant.   Our favourite
implementation interns small integers and simple strings (and
apparently also equivalent strings and integers created on the same
line(?)), for optimisation purposes.  These are really exceptional.  
You shouldn't find this behaviour in defined classes for instance. 
The behaviour of tuples in this regard as much more 'normal.'



More information about the Python-list mailing list