I\'m making a Python parser, and this is really confusing me:
>>> 1 in [] in \'a\'
False
>>> (1 in []) in \'a\'
TypeError: \'in &
Python does special things with chained comparisons.
The following are evaluated differently:
x > y > z # in this case, if x > y evaluates to true, then
# the value of y is being used to compare, again,
# to z
(x > y) > z # the parenth form, on the other hand, will first
# evaluate x > y. And, compare the evaluated result
# with z, which can be "True > z" or "False > z"
In both cases though, if the first comparison is False
, the rest of the statement won't be looked at.
For your particular case,
1 in [] in 'a' # this is false because 1 is not in []
(1 in []) in a # this gives an error because we are
# essentially doing this: False in 'a'
1 in ([] in 'a') # this fails because you cannot do
# [] in 'a'
Also to demonstrate the first rule above, these are statements that evaluate to True.
1 in [1,2] in [4,[1,2]] # But "1 in [4,[1,2]]" is False
2 < 4 > 1 # and note "2 < 1" is also not true
Precedence of python operators: http://docs.python.org/reference/expressions.html#summary