Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
boolean
#1
Can anybody explain why:

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

is

False

Thank you
Reply
#2
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
Reply
#3
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
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020