[Tutor] if n == 0 vs if not n

Kent Johnson kent37 at tds.net
Thu Oct 8 20:29:43 CEST 2009


On Mon, Oct 5, 2009 at 9:13 PM, Luke Paireepinart
<rabidpoobear at gmail.com> wrote:

> Actually, I just realized that "not" has higher precedence than "==" so this
> is really checking if (not n) is equal to 0, not if (n == 0) is (not) True.

No, "not" is lower precedence than "==". See
http://docs.python.org/reference/expressions.html#summary

> Anyone have some counter-examples to n != 0 being the same as "not n == 0"?

Well, you can create a pathological class where they are different:

In [17]: class funky(object):
   ....:     def __eq__(self, other):
   ....:         return True
   ....:     def __ne__(self, other):
   ....:         return True

In [18]: f = funky()

In [19]: f != 0
Out[19]: True

In [20]: f == 0
Out[20]: True

In [21]: not f == 0
Out[21]: False


For a less contrived example, if n is a numpy array, n==0 is also a
numpy array but (not n != 0) gives an error:

In [1]: from numpy import *

In [2]: a = array( [ 0, 10, 20, 30, 40 ] )

In [3]: a== 0
Out[3]: array([ True, False, False, False, False], dtype=bool)

In [5]: not a!= 0
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)

C:\Project\MangoLib\<ipython console> in <module>()

ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()

Kent


More information about the Tutor mailing list