Why in Python it is evaluated this way:
>>> False is False is False
True
but when tried with parenthesis is behaving as expected:
>>> (False is False) is False
False
Why in Python it is evaluated this way:
>>> False is False is False
True
but when tried with parenthesis is behaving as expected:
>>> (False is False) is False
False
Chaining operators like a is b is c
is equivalent to a is b and b is c
.
So the first example is False is False and False is False
, which evaluates to True and True
which evaluates to True
Having parenthesis leads to the result of one evaluation being compared with the next variable (as you say you expect), so (a is b) is c
compares the result of a is b
with c
.
Quoting Python official documentation,
Formally, if
a
,b
,c
, ...,y
,z
are expressions andop1
,op2
, ...,opN
are comparison operators, thena op1 b op2 c ... y opN z
is equivalent toa op1 b and b op2 c and ... y opN z
, except that each expression is evaluated at most once.
So, False is False is False
is evaluated as
(False is False) and (False is False)
The second False is False
expression uses the second False
in the original expression, which effectively translates to
True and True
That is why the first expression evalutes to be True
.
But in the second expression, the evaluation sequence is as follows.
(False is False) is False
Which is actually
True is False
That is why the result is False
.
Your expression
False is False is False
is treated as
(False is False) and (False is False)
So you get
True and True
and that evaluates to True
.
You can use this kind of chaining with other operators too.
1 < x < 10
I think that False is False is False
means (False is False) and (False is False)
, but (False is False) is False
means :
>>> (False is False) is False
False
>>> a_true = (False is False)
>>> a_true
True
>>> a_true is False
False
So, you get the result.
>>> False is False is False
True
In this case, each of False
pair is evaluated. The first two False is evaluated, if it's True
, then the second and the third False
is evaluated and return the result.
In this case, False is False is False
is equivalent to and
of results of 2 commands False is False