Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is x==x ever False in Python?

I stumbled upon this line of code in SciPy's source, in the stats module:

return 1.0*(x==x)

Is this return something other than 1.0? In other words, is there any value of x such that x == x holds False?

like image 722
astrojuanlu Avatar asked Apr 21 '12 13:04

astrojuanlu


People also ask

Is False == False Python?

Python interprets multiple (in)equalities the way you would expect in Math: In Math a = b = c mean all a = b , b = c and a = c . So True is False == False means True == False and False == False and True == False , which is False . For boolean constants, is is equivalent to == .

What does == False mean in Python?

In Boolean logic "False" is a negative truth-value representing nothing.

What does == true mean in Python?

It's used to represent the truth value of an expression. For example, the expression 1 <= 2 is True , while the expression 0 == 1 is False .

How do you know if a Python is False?

You can check if a value is either truthy or falsy with the built-in bool() function. According to the Python Documentation, this function: Returns a Boolean value, i.e. one of True or False .


2 Answers

According to the IEEE 754 standard not-a-number (NaN) must always compare false, no matter what it is compared to.

Python 2.7.2+ (default, Oct  4 2011, 20:06:09) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> x=float("NaN")
>>> x==x
False
like image 140
user1202136 Avatar answered Sep 20 '22 20:09

user1202136


A user-defined type can override the equality operator to do whatever you want:

Python 3.2.2 (default, Feb 10 2012, 09:23:17) 
[GCC 4.4.5 20110214 (Red Hat 4.4.5-6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class A:
...     def __eq__(self, other):
...         return False
... 
>>> x=A()
>>> x==x
False
like image 24
James Avatar answered Sep 17 '22 20:09

James