I’m making a Python parser, and this is really confusing me:
>>> 1 in [] in 'a'
False
>>> (1 in []) in 'a'
TypeError: 'in <string>' requires string as left operand, not bool
>>> 1 in ([] in 'a')
TypeError: 'in <string>' requires string as left operand, not list
How exactly does in work in Python, with regards to associativity, etc.?
Why do no two of these expressions behave the same way?
1 in [] in 'a'is evaluated as(1 in []) and ([] in 'a').¹Since the first condition (
1 in []) isFalse, the whole condition is evaluated asFalse;([] in 'a')is never actually evaluated, so no error is raised.We can see how Python executes each statement using the
dismodule:[]is only evaluated once. This doesn’t matter in this example but if you (for example) replaced[]with a function that returned a list, that function would only be called once (at most). The documentation explains also this.