Search code examples
pythonlistoperatorsoperator-precedence

"in" operator chaining ( True in [True] in [True] OUTPUT: False )


I'm trying to figure out in what order this code runs:

print( True in [True] in [True] )
False

even though:

print( ( True in [True] ) in [True] )
True

and:

print( True in ( [True] in [True] ) )
TypeError

If the first code is neither of these two last ones, then what?


Solution

  • in is comparing with chaining there so

    True in [True] in [True]
    

    is equivalent to (except middle [True] is evaluated once)

    (True in [True]) and ([True] in [True])
    

    which is

    True and False
    

    which is

    False
    

    This is all similar to

    2 < 4 < 12
    

    operation which is equivalent to (2 < 4) and (4 < 12).