Is vs Equality Operator

Gary Herron gherron at islandtraining.com
Thu May 1 05:10:45 EDT 2008


Good Z wrote:
> Hello,
> I am having problem in using is. Here is what i am doing.

Short answer:  Use == for equality.    Don't use "is".  Ever!  
(Especially if you are a newbie.)

Longer answer:  In a dozen years of programming Python, the only time I 
use "is" is when testing for something like 
  if x is None
but, even then
  if x == None
works just as well, and in any case, there is usually a better way.  
(See below.)

Don't use "is" until you can explain the following
 >>> 11 is 10+1
True
 >>> 100001 is 100000+1
False


>
> x=''
> if x is None or x is '':
>         return 1

Both None and an empty string (and empty lists, empty dictionaries, 
empty sets, and numeric values of 0 and 0.0) all evaluate a False in an 
if statement, so the above if statement can be written as

  if not x:
      return 1

If you have to test for None, just do
  if not x:

If you have to differentiate between a value of None and something that 
evaluates to False (e.g., and empty list) then do
  if x is None:
    # handle None explicitly
  elif not x:
    # handle empty list

>
> 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.
>
> Mike
>
> ------------------------------------------------------------------------
> Be a better friend, newshound, and know-it-all with Yahoo! Mobile. Try 
> it now. 
> <http://us.rd.yahoo.com/evt=51733/*http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ%20> 
>
> ------------------------------------------------------------------------
>
> --
> http://mail.python.org/mailman/listinfo/python-list




More information about the Python-list mailing list