Why does “1 in range(2) == True” evaluate to False? [duplicate]

Posted on

Question :

Why does “1 in range(2) == True” evaluate to False? [duplicate]

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?

Answer #1:

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.

Answer #2:

Try to write

(1 in range(2)) == True

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

Answered By: OptimusCrime

Leave a Reply

Your email address will not be published.