Python Forum

Full Version: boolean
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Can anybody explain why:

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

is

False

Thank you
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
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