David Perlman wrote: > This helps convince me that I still don't understand why the original > code snippet worked at all. :) > > These code examples make perfect sense. This one doesn't, and > appears to be an inconsistency: > > >>> word2 = 'hello' > >>> item = 'e' > >>> item in word2 > True > >>> item == item in word2 > True > >>> (item == item) in word2 > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: 'in <string>' requires string as left operand > >>> item in word2 > True > >>> item == True > False > >>> item == (item in word2) > False > > Notice that forcing the precedence of "in" and "==" using parentheses > gives either False or an error, but without parentheses, it's True. > So what's going on?
'==' and 'in' are both comparison operators and they have equal precedence. Python semantics for comparison operators have a wrinkle that usually makes sense but in this case is confusing. In general, if op1 and op2 are comparison operators, a op1 b op2 c means the same as a op1 b and b op2 c This is handy in the case, for example, of a < b < c which has its conventional meaning of a < b and b < c but for the current question item == item in word this is the same as item == item and item in word which is not what you would expect. http://docs.python.org/ref/comparisons.html Kent _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor