I have a question about identity in python, i'm a beginner in python and i have read some courses on "is" keyword and "is not". And i don't understand why the operation "False is not True is not True is not False is not True" equals False in python ? For me this operation have to return True.
3 Answers
Python chains comparisons:
Formally, if
a, b, c, …, y, zare expressions andop1, op2, …, opNare comparison operators, thena op1 b op2 c ... y opN zis equivalent toa op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.
Your expression is:
False is not True is not True is not False is not True
Which becomes:
(False is not True) and (True is not True) and (True is not False) and (False is not True)
Which is equivalent to:
(True) and (False) and (True) and (True)
Which is False.
- 23,859
- 5
- 60
- 99
-
The reason I know about this is because the [first question](https://stackoverflow.com/questions/9284350/why-does-1-in-1-0-true-evaluate-to-false) I asked on Stack Overflow, 7 years and 7 months ago, was another incarnation of the question, although at the time I didn't realise it. – Peter Wood Oct 09 '19 at 16:23
-
No problem. Done – Barb Oct 09 '19 at 17:03
is relates to identity.
When you ask if x is y, you're really asking are x and y the same object? (Note that this is a different question than do x and y have the same value?)
Likewise when you ask if x is not y, you're really asking are x and y different objects?
Specifically in regards to True and False, Python treats those as singletons, which means that there is only ever one False object in an entire program. Anytime you assign somnething to False, that is a reference to the single False object, and so all False objects have the same identity.
- 29,573
- 7
- 33
- 58
-
But aren't `False` and `True` singletons? Or is it just `None` which is? edit: [they are](https://www.python.org/dev/peps/pep-0285/) – Peter Wood Oct 09 '19 at 16:06
-
1
-
1This isn't to do with identity it's to do with how Python chains comparisons. – Peter Wood Oct 09 '19 at 16:14
You are dealing with logic. It helps to think about True = 1 and False = 0.
Think about it this way. 0 is not 1, that will return True because the number 0 is not the number 1 and is a true statment. Same concept with True and False
0 is not 1
#this will return False
False is not True
#the computer reads this in the exact same manner.
- 90
- 8