Is vs Equality Operator

Christian Heimes lists at cheimes.de
Thu May 1 08:07:53 EDT 2008


Good Z schrieb:
> Hello, 
> I am having problem in using is. Here is what i am doing.
> 
> x=''
> if x is None or x is '':
>         return 1
> 
> The above statement does not return value 1.
> 
> If i changed the above check to 
> if x == None or x == '':
>         return 1
> Now it works fine.
> 
> Any idea. What is happening here. I am using python 2.4.4 on ubuntu.

Never use the identity operator "is" on strings and numbers! In most of
the cases it won't do what you are expecting.

The behavior can be explained with with a simple analogy. You have a
street with a STOP sign on both ends. The stop sign on the near end is
equal to the stop sign on the far end. Both have the same form, colors
and meaning. The stop signs are also equal to every other stop sign in
your town. However the stop signs are NOT identical. They occupy two
different places and they are made from two totally different sets of atoms.

When you want to know if the stop sign on the near end is a stop sign,
you have to use the equality == operator. But if you want to check if
you are referring to exactly the one and only stop sign at the near end
of your road and no other sign in the universe you have to use 'is'.

HTH

Christian




More information about the Python-list mailing list