Python Forum
boolean - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: boolean (/thread-22657.html)



boolean - bloomyhood - Nov-21-2019

Can anybody explain why:

'b' in 'abc' == 'a' in 'abc'

is

False

Thank you


RE: boolean - ThomasL - Nov-21-2019

Must have something to do with the "in" keyword
print('b' in 'abc' == 'a' in 'abc')
print(('b' in 'abc') == 'a' in 'abc')
print('b' in 'abc' == ('a' in 'abc'))
print(('b' in 'abc') == ('a' in 'abc'))
Output:
False False False True



RE: boolean - snippsat - Nov-21-2019

It has to do with chaining comparison operators.
So what's really happens is:
>>> 'b' in 'abc' == 'a' in 'abc'
False

>>> # The chaining is 
>>> ('b' in 'abc') and ('abc' == 'a') and ('a' in 'abc')
False

>>> # After ('abc' == 'a') the result is False and last ('a' in 'abc') is not evaluated   
>>> ('abc' == 'a') 
False
Should avoid to use == like this as it can give unexpected result.
If most use it so dos () break the chaining.
>>> ('b' in 'abc') == ('a' in 'abc')
True