Python: False == False in [True] ?

Let get straight to the expression False == False in [True], what you think this expression evaluates to True or False. Fire up your terminal and try, if you get the answer that you have thought of, congratulations!. My guess was wrong :p. Let break down the expression to see how it is evaluated in Python.

# False == False in [True] 
>>> False == False
True
>>> False in [True]
False
>>> (False == False) in [True]
True
>>>False == (False in [True])
True
# but the weird part is when we run
>>> False == False in [True]
False

Isn't this a bit weird? But it is not so, When we look at the expression the way python interprets the expression, things start making sense.

>>> False == False and False in [True]
False

On a bit further looking. I parse the expression to get the Abstract Syntax Tree, which tell a lot about the expression evaluation.

>>> import ast, pprint
>>> pprint.pprint(ast.dump(ast.parse('False == False in [True]')), indent=4)
('Module(body=[Expr(value=Compare(left=Constant(value=False, kind=None), '
 'ops=[Eq(), In()], comparators=[Constant(value=False, kind=None), '
 'List(elts=[Constant(value=True, kind=None)], ctx=Load())]))], '
 'type_ignores=[])')

From the above output of AST you can see that [Eq(), In()] are compound operators and in python, the precedence of these operations is the same.

comparisons, including tests, which all have the same precedence chain from left to right

The below mentioned operators have the same precedence.

in, not in, is, is not, <, <=, >, >=, <>, !=, ==

So, when Python tries to evaluate the expression False == False in [True], it encounters the operators is and == which have the same precedence, so it performs chaining from left to right. – from stackoverflow[0]

# so above expression on evaluating from left to right is done like this.
>>> False == False and False in [True]

Cheers!

References – [0] https://stackoverflow.com/questions/31354429/why-is-true-is-false-false-false-in-python – [1] https://stackoverflow.com/questions/12658197/what-is-the-operator-precedence-when-writing-a-double-inequality-in-python-expl – [2] https://www.youtube.com/watch?v=mRPU3l54Z7I&list=PLWBKAf81pmOamJfoHz4oRdieWQysmUkaW

#100DaysToOffload #Python