Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does `True == False is False` evaluate to False? [duplicate]

Tags:

python

I get some rather unexpected behavior on an expression that works with == but not with is:

>>> (True == False) is False True >>> True == (False is False) True >>> True == False is False False >>> id(True) 8978640 >>> id(False) 8978192 >>> id(True == False) 8978192 >>> id(False is False) 8978640 
like image 278
raylu Avatar asked Jun 19 '13 22:06

raylu


People also ask

Why is true and false false in Python?

In Python, the two Boolean values are True and False (the capitalization must be exactly as shown), and the Python type is bool. In the first statement, the two operands evaluate to equal values, so the expression evaluates to True; in the second statement, 5 is not equal to 6, so we get False.

Why is false && true false?

If the left side of the expression is "falsey", the expression will return the left side. If the left side of the expression is "truthy", the expression will return the right side. That's it. So in false && false , the left side is "falsey", so the expression returns the left side, false .

What does false or true evaluate to?

FALSE evaluates to TRUE, so xor(FALSE, TRUE) evaluates to TRUE. On the other hand if the first argument was changed to 5 == 5 and the second argument was unchanged then both arguments would have been TRUE, so xor(TRUE, TRUE) would have evaluated to FALSE.


1 Answers

Because in fact that's a chained comparison, so

True == False is False 

is equivalent to

(True == False) and (False is False) 

This can be surprising in this case, but lets you write 1 <= x < 4 unlike in other languages like C.

like image 81
jorgeca Avatar answered Nov 05 '22 08:11

jorgeca