Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python comparison operator precedence

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?

>>> -1 < 0 == False
True

>>> (-1 < 0) == False
False

I would expect both be evaluated to False. Why is it not the case?

like image 522
Yichun Avatar asked Aug 07 '19 18:08

Yichun


People also ask

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?

What are the 4 Python comparison operators?

Summary. A comparison operator compares two values and returns a boolean value, either True or False . Python has six comparison operators: less than ( < ), less than or equal to ( <= ), greater than ( > ), greater than or equal to ( >= ), equal to ( == ), and not equal to ( != ).

Does || or && have higher precedence?

The logical-AND operator ( && ) has higher precedence than the logical-OR operator ( || ), so q && r is grouped as an operand. Since the logical operators guarantee evaluation of operands from left to right, q && r is evaluated before s-- .

What is the correct order of precedence in Python?

Answer: The correct order of precedence is given by PEMDAS which means Parenthesis (), Exponential **, Multiplication *, Division /, Addition +, Subtraction -.


1 Answers

Python has a really nice feature - chained comparison, like in math expressions, so

-1 < 0 == False

is actually a syntactic sugar for

-1 < 0 and 0 == False

under the hood.

like image 145
Roman Susi Avatar answered Sep 23 '22 06:09

Roman Susi