5

I came across this expression, which I thought should evaluate to True but it doesn't.

>> s = 1 in range(2)
>> s == True
>> True

Above statement works as expected but when this:

1 in range(2) == True

is executed, it evaluates to False.

I tried searching for answers but couldn't get a concrete one. Can anyone help me understand this behavior?

Pika Supports Ukraine
  • 3,612
  • 10
  • 26
  • 42
Raghav salotra
  • 820
  • 1
  • 11
  • 23

2 Answers2

12

1 in range(2) == True is an operator chain, just like when you do 0 < 10 < 20

For it to be true you would need

1 in range(2)

and

range(2) == True

to be both true. The latter is false, hence the result. Adding parenthesis doesn't make an operator chaining anymore (some operators are in the parentheses), which explains (1 in range(2)) == True works.

Try:

>>> 1 in range(2) == range(2)
True

Once again, a good lesson learned about not equalling things with == True or != False which are redundant at best, and toxic at worst.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

Try to write

(1 in range(2)) == True

It has to do with parsing and how the expression is evaluated.

OptimusCrime
  • 14,662
  • 13
  • 58
  • 96
  • How exactly *is* the expression parsed without parentheses? If I run `1 in (range(2) == True)`, it throws `TypeError: argument of type 'bool' is not iterable`. – Ryan C. Thompson Feb 23 '18 at 08:58
  • @Optimus Can you please provide the detailed explanation of this behavior. How parsing is causing this behavior? – Raghav salotra Feb 23 '18 at 08:58