7.4 Comparison Operators
Python's comparison operators — == != < > <= >= — comparison chaining, and comparing tuples lexicographically for version numbers.
What Are They?
Operators that compare two values and always return a bool.
Why Are They Used?
The foundation of every conditional (if, while) in a program.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
< | Less than | 5 < 3 | False |
> | Greater than | 5 > 3 | True |
<= | Less than or equal | 5 <= 5 | True |
>= | Greater than or equal | 5 >= 6 | False |
Comparison Chaining
What Is It?
Writing a < b < c evaluates as (a < b) and (b < c) — both comparisons must hold, and b is only evaluated once. Covered in more depth in 7.12 Chained Comparisons.
>>> 1 < 2 < 3
True
Version Comparison
What Is It?
Comparing tuples element-by-element — exactly how version numbers like (1, 5, 0) are typically compared, since Python compares tuples lexicographically (the first differing element decides the result).
>>> v1 = (1, 5, 0)
>>> v2 = (1, 4, 9)
>>> v1 > v2 # compares 1==1, then 5>4 decides it
True
Quick Interview Answer
“Comparison operators (
== != < > <= >=) always return abooland are the foundation of everyif/whilecondition. Python allows chaining them directly —a < b < c— which evaluates as(a < b) and (b < c), withbevaluated only once. A practical use of comparison is comparing tuples lexicographically, which is exactly how version tuples like(1, 5, 0)are typically compared.”
Common Mistakes
- Using
==on floats expecting exact equality — floating-point rounding means0.1 + 0.2 == 0.3isFalse; compare with a tolerance instead (abs(a - b) < 1e-9). - Using
iswhere==was intended —iscompares identity, not value, covered fully in 7.8 Identity Operators.
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form