Is vs Equality Operator

Michael Mabin d3vvnull at gmail.com
Thu May 1 08:08:22 EDT 2008


'is' tests for identity (variable references the same memory location) while
'==' tests for equality.  Though it's probably best to use 'is' with more
complex classes and not the simpler built-in types like integers.
See how 'is' works for lists below:

>>> l1 = [1,2,3,4]
>>> l3 = [1,2,3,4]
>>> l1 == l3
True
>>> l1 is l3
False
>>> l2 = l1
>>> l1 is l2
True

l1 and l3 are equal because they contain the same elements. But they are not
identical because they reference different list objects in memory.  On the
other hand, l1 and l2 are identical, so using 'is' in this case tests True.

'is' will be true of the objects tested have the same address in memory.

On Thu, May 1, 2008 at 4:10 AM, Gary Herron <gherron at islandtraining.com>
wrote:

> 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
> >
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
| _ | * | _ |
| _ | _ | * |
| * | * | * |
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080501/9a7191ff/attachment-0001.html>


More information about the Python-list mailing list