Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparison operators and 'is' - operator precedence in python?

So I was looking at some code online and I came across a line (at line 286):
if depth > 0 and best <= -MATE_VALUE is None and nullscore > -MATE_VALUE:

The part I had trouble understanding was the best <= -MATE_VALUE is None.

So I fired up the interpreter to see how a statement such as value1 > value2 is value3 work.
So I tried

>>> 5 > 2 is True
False

>>> (5 > 2) is True 
True

>>> 5 > (2 is True) 
True


My Question

Why is 5 > 2 is True not True? And how do these things generally work?

Thanks.

like image 611
Kidus Avatar asked Aug 24 '15 12:08

Kidus


People also ask

How does Python compare operators to precedence?

Almost all the operators have left-to-right associativity. For example, multiplication and floor division have the same precedence. Hence, if both of them are present in an expression, the left one is evaluated first. Note: Exponent operator ** has right-to-left associativity in Python.

Do all comparison operators have the same precedence in Python?

All comparison operations in Python have the same priority, which is lower than that of any arithmetic, shifting or bitwise operation. Thus "==" and "<" have the same priority, why would the first expression in the following evaluate to True , different from the 2nd expression?

Which operator has more precedence in Python?

Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want.

What are comparison operators in Python?

A comparison operator in python, also called python relational operator, compares the values of two operands and returns True or False based on whether the condition is met.


2 Answers

You're seeing python's operator chaining working

5 > 2 is True

Is equivalent to

5>2 and 2 is True

You can see this in that

>>> 5>2 is 2

Returns True.

like image 134
muddyfish Avatar answered Oct 16 '22 08:10

muddyfish


First, 5 > 2 is True is equivalent to (5 > 2) and (2 is True) because of operator chaining in python (section 5.9 here).

It's clear that 5 > 2 evaluates to True. However, 2 is True will evaluate to False because it is not implicitly converted to bool. If you force the conversion, you will find that bool(2) is True yields True. Other statements such as the if-statement will do this conversion for you, so if 2: will work.

Second, there is an important difference between the is operator and the == operator (taken from here):

Use is when you want to check against an object's identity (e.g. checking to see if var is None). Use == when you want to check equality (e.g. Is var equal to 3?).

>> [1,2] is [1,2]
False

>> [1,2] == [1,2]
True

While this does not have an immediate impact on this example, you should keep it in mind for the future.

like image 44
Daniel Lenz Avatar answered Oct 16 '22 07:10

Daniel Lenz