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?
CodePudding user response:
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)
.
CodePudding user response:
print( True in [True] in [True] )
This is actually interpreted as - True in [True] and [True] in [True]
which gives you false because it becomes - True and False
print( ( True in [True] ) in [True] )
The ( True in [True] )
is checked first, so you get True in [True]
which is True.
print( True in ( [True] in [True] ) )
The second part is checked, before the first because of parenthesis which changes the order, so it becomes - True in True
. And True
which is a boolean, is not a iterable, so you cannot use in
, and then you get TypeError