0

I started learning python but I've noticed something unsual, something that I do not understand, why the expression provided below it's evaluated to false even it is true??

l = [1,2,3,4,5,"Hi"]
"Hi" in l  # returns True
"Hi" in l == True # returns False

J.Doe
  • 35
  • 1
  • 4

1 Answers1

4

"Hi" in l == True is evaluated as ("Hi" in l) and (l == True) which is False.

Explanation from documentation:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z

sanyassh
  • 8,100
  • 13
  • 36
  • 70
  • Actually it’s evaluated as `'Hi' in (l == True)` which is `'Hi' in False` – N Chauhan May 09 '19 at 18:49
  • 1
    @NChauhan If that were true, `'Hi' in l == True` would cause a type error, just like `'Hi' in (l == True)` and `'Hi' in False` do. – sepp2k May 09 '19 at 18:54
  • 2
    @sepp2k Ah my mistake. – N Chauhan May 09 '19 at 18:55
  • It's pretty weird that `in` is considered to be the same kind of comparison operator as `<` and `==`. Is there any reasonable case where you would want to include it in a chain like this? – Barmar May 09 '19 at 19:06
  • @Barmar IMHO there is no such case where I will use `in` comparison in a chain. Only simple and clear chains like `0 < x < 1` are commonly used. `in` in a chain produces too much mustakes and confusion. – sanyassh May 09 '19 at 19:12
  • So you think it's not intentional, just a side effect of the prcedence rules? – Barmar May 09 '19 at 19:14
  • I think yes, just a `status-by-design` thing. – sanyassh May 09 '19 at 19:15