4

This what I got while fiddling with the python interpreter

[mohamed@localhost ~]$ python
Python 2.7.5 (default, Apr 10 2015, 08:09:14) 
[GCC 4.8.3 20140911 (Red Hat 4.8.3-7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 'a' in 'abc'
True
>>> 'a' in 'abc' == True
False
>>> 'a' in 'abc' == False
False 
>>> ('a' in 'abc') == True
True
>>> ('a' in 'abc') == False
False


>>> ('a' in 'abc' == True) or ('a' in 'abc' == False)
False
>>> (('a' in 'abc') == True) or (('a' in 'abc') == False)
True

My question is why using parenthesis gives me the intended, and more logically sound, output?

user2864740
  • 60,010
  • 15
  • 145
  • 220
user100169
  • 43
  • 3
  • (The combinations with `or` is just an extension of the first condition.) – user2864740 Jul 18 '15 at 04:36
  • 3
    Another duplicate [Why does (1 in \[1,0\] == True) evaluate to False](http://stackoverflow.com/questions/9284350/why-does-1-in-1-0-true-evaluate-to-false) – Bhargav Rao Jul 18 '15 at 04:39
  • Also possible duplicate of [Why is `True is False == False`, False in Python](http://stackoverflow.com/questions/31354429/why-is-true-is-false-false-false-in-python/31354514#31354514) – Mazdak Jul 18 '15 at 05:13

1 Answers1

9

Because of operator chaining, in and == do not behave well together.

'a' in 'abc' == True

Transforms to -

'a' in 'abc' and 'abc' == True

Reference from documentation -

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).

The similar thing happens for in and == .

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176