Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

('a' in 'abc' == True) evaluates to False [duplicate]

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?

like image 331
user100169 Avatar asked Jan 07 '23 23:01

user100169


1 Answers

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

like image 92
Anand S Kumar Avatar answered Jan 15 '23 21:01

Anand S Kumar