Python statement giving unexpected answer
boolean, python
Solution
Operator chaining at work.
'a' in 'ab' == True
is equivalent to
'a' in 'ab' and 'ab' == True
Take a look:
>>> 'a' in 'ab' == True
False
>>> ('a' in 'ab') == True
True
>>> 'a' in ('ab' == True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable
>>> 'a' in 'ab' and 'ab' == True
False
From the docs linked above:
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).
Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.
The real advantage of operator chaining is that each expression is evaluated once, at most. So with `a < b < c`, `b` is only evaluated once and then compared first to `a` and secondly (if necesarry) to `c`.
As a more concrete example, lets consider the expression `0 < x < 5`. Semantically, we mean to say that x is in the closed range [0,5]. Python captures this by evaluating the logically equivalent expression `0 < x and x < 5`. Hope that clarifies the purpose of operator chaining somewhat.
Problem
``` print 'a' in 'ab' ``` prints `True`, while ``` print 'a' in 'ab' == True ``` prints `False`. Any guess why?