Confusion About Operator Precedence in Python
Asked by
careful listener
Hey everyone! I have a pretty straightforward question about operator precedence in Python. I want to know which operators have higher precedence: the equality operators (==, !=) or the comparison operators (>, =, <=). According to the Python documentation, they all seem to have the same precedence and associativity. However, I tested this with the expression `print(5 < 5 == 5 <= 5)`, and got `False`.
Based on the documentation, I expected it to return `True`. Here's my reasoning: if we evaluate it from left to right, `5 < 5` gives `False`, so we get `0 == 5 <= 5`. Then `0 == 5` results in `False`, leaving us with `0 <= 5`, which should evaluate to `True`. So I'm a bit puzzled. What's your take on this? Thanks in advance!
Answers
If you find yourself tangled in these precedence rules often, it might be easier to just rewrite your expression to avoid ambiguity.
Reply to this answer
The operators do have the same precedence, but Python evaluates them using chaining. Essentially, `5 < 5 == 5 <= 5` is interpreted as `5 < 5 and 5 == 5 and 5 <= 5`. To get the evaluation youโre expecting, you should use parentheses like this: `(5 < 5) == (5 <= 5).`
Reply to this answer
Yeah, the expression is effectively wrapped in parentheses from Python's perspective, like this: `print((5 < 5) == (5 <= 5))`. It's not typical behavior in languages that I've worked with, so I get your confusion.
Reply to this answer
Add your answer
Answers are reviewed before publication.
+!intermission snack: You nailed it! Chaining is definitely the key here. Just a small correction though: if you want to replicate the exact scenario you described, it should be `((5 < 5) == 5) <= 5`.
Fermata: You're right, thanks for clarifying that!