Python's comparison operators work on numbers by their mathematical value, on strings and sequences lexicographically, element by element, and can be chained in a single expression, so checking that x is between two bounds can be written without repeating x. == checks for value equality, calling the object's __eq__ method, which is different from the is operator, which checks whether two names refer to the exact same object in memory.
1Understanding Comparison Operators
Python's comparison operators work on numbers by their mathematical value, on strings and sequences lexicographically, element by element, and can be chained in a single expression, so checking that x is between two bounds can be written without repeating x. == checks for value equality, calling the object's __eq__ method, which is different from the is operator, which checks whether two names refer to the exact same object in memory.
Chained comparisons like checking that a value is between two bounds are evaluated the same way as writing the two conditions separately joined by `and`, but the middle value is only evaluated once — more concise and slightly more efficient than writing the `and` version by hand.
print(5 == 5.0)
print(1 < 5 < 10)
print("apple" < "banana")2Practical Example
Here is a real-world application of Comparison Operators showing how it is used in production Python code.
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
print(Point(1, 2) == Point(1, 2))3Best Practices
Follow these guidelines when working with Comparison Operators:
1. Use == for value equality and is only for identity checks, like comparing to None
2. Take advantage of chained comparisons instead of writing them out with and
3. Override __eq__ (and usually __hash__ alongside it) on custom classes if you want == to compare by value instead of identity
Tip: Chained comparisons like checking that a value is between two bounds are evaluated the same way as writing the two conditions separately joined by `and`, but the middle value is only evaluated once — more concise and slightly more efficient than writing the `and` version by hand.
print(5 == 5.0)
print(1 < 5 < 10)
print("apple" < "banana")