"is" and "=="

Lexy Zhitenev zhitenev at cs.vsu.ru
Tue Mar 11 18:28:59 CET 2003


"Dagur Páll Ammendrup" wrote: news:b4l3t5$28hs$1 at mikill.isnet.is...
> I was wondering when == should be used and when "is". I like using "is"
> when comparing strings and stuff but maybe I shouldn't?
>

Unfortunately, you shouldn't. I like using 'is' too, but 'is' must be used
to test for object identity, and '==' - to test for object equality. In
other words 'a is b' equals 'id(a) == id(b)'

When you have two equal strings, they may not be the same string objects.
See:
>>> a = '12345'
>>> b = a
>>> b == a
1
>>> b is a
1
>>> c = '123' + '45'
>>> a == c
1
>>> a is c
0

I couldn't write "c='12345'", because due to optimizing, c could have been
the same object as a and b.

Good Luck, Lexy.







More information about the Python-list mailing list