Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 583
Raghav salotra Avatar asked Feb 23 '18 08:02

Raghav salotra


2 Answers

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.

like image 139
Jean-François Fabre Avatar answered Nov 14 '22 23:11

Jean-François Fabre


Try to write

(1 in range(2)) == True

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

like image 1
OptimusCrime Avatar answered Nov 14 '22 23:11

OptimusCrime