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
>>> False in [True]
>>> (False == False) in [True]
>>>False == (False in [True])
# but the weird part is when we run
>>> False == False in [True]

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]

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())]))], '

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]


References – [0] – [1] – [2]

#100DaysToOffload #Python