is and ==

Steve Purcell stephen_purcell at yahoo.com
Mon Feb 26 11:50:23 EST 2001


Daniel Klein wrote:
> Is there a functional difference between 'is' and '==' ?  If there is, I can't
> find it.

There is indeed a difference.

'is' is an identity test, and '==' is an equality test:

>>> a = [] 
>>> b = []
>>> a is b
0
>>> a == b
1

In many cases for standard python types, you won't find a difference, though.
String literals are invisibly re-used internally by Python ("interned"):

>>> a = "hello"
>>> b = "hello"
>>> a is b
1
>>> a == b
1

But beware of:

>>> a = "hel" + "lo"
>>> b = "hel" + "lo"
>>> a is b
0
>>> a == b
1


Integers are both equal *and* identical:

>>> a = 1
>>> b = 1
>>> a is b
1
>>> a == b
1



-Steve

-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Get servlets at http://pyserv.sourceforge.net/
"Even snakes are afraid of snakes." -- Steven Wright




More information about the Python-list mailing list