Skip to content Skip to sidebar Skip to footer

What Does X In Range(...) == Y Mean In Python 3?

I just stumbled upon the following line in Python 3. 1 in range(2) == True I was expecting this to be True since 1 in range(2) is True and True == True is True. But this outputs F

Solution 1:

This is due to the fact that both operators are comparison operators, so it is being interpreted as operator chaining:

https://docs.python.org/3.6/reference/expressions.html#comparisons

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

So it is equivalent to:

>>> (1inrange(2)) and (range(2) == True)
False

Post a Comment for "What Does X In Range(...) == Y Mean In Python 3?"