Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A question about identity and boolean in Python3

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.

like image 431
Progear Avatar asked Jul 24 '26 11:07

Progear


2 Answers

Python chains comparisons:

Formally, if a, b, c, …, y, z are expressions and op1, op2, …, opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a 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.

like image 180
Peter Wood Avatar answered Jul 28 '26 11:07

Peter Wood


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.

like image 20
John Gordon Avatar answered Jul 28 '26 13:07

John Gordon