Comparison (Relational) Operators
Comparison operators are used to compare two values. They are the foundation of decision-making in Python, as they evaluate to a boolean value: True or False. These are most commonly used in if statements and while loops to control the flow of a program.
The Core Comparison Operators
Equal ==
Checks if the values of two operands are equal.
Pyground
Check if the value of `a` is equal to 10.
Expected Output:
a == 10: True a == b: True a == c: False
Output:
Chained Comparisons
Python allows for a wonderfully readable feature called chained comparisons. You can write a sequence of comparisons that reads like natural language.
a < b < c is a shortcut for (a < b) and (b < c).
Pyground
Check if a person's age is between 18 and 30 (inclusive).
Expected Output:
Is the age 25 between 18 and 30? True Is the age 35 between 18 and 30? False
Output:
Chained comparisons are efficient. In a < b < c, c is only evaluated if a < b is True. This is known as “short-circuiting.”
Comparing Different Types
- Numbers: Integers and floats are compared based on their mathematical value.
10 == 10.0isTrue. - Strings: Strings are compared lexicographically (alphabetical order).
'apple' < 'banana'isTrue. - Lists/Tuples: Sequences are compared element by element from left to right. The comparison stops as soon as a difference is found.
- Unrelated Types: In Python 3, comparing completely unrelated types like a number and a string with ordering operators (
<,>) will raise aTypeError.
Pyground
Compare two lists lexicographically.
Expected Output:
Is [1, 2, 5] < [1, 2, 10]? True
Output:
Customizing Comparisons for Your Objects
You can define how instances of your own classes are compared by implementing special “rich comparison” methods.
__eq__(self, other)for==__ne__(self, other)for!=__lt__(self, other)for<__gt__(self, other)for>__le__(self, other)for<=__ge__(self, other)for>=
Pyground
Create a Task class where tasks are compared based on their priority.
Expected Output:
task1 < task2: True task1 == task3: True task1 >= task2: False
Output:
The @functools.total_ordering decorator is a convenient helper. If you define __eq__ and at least one of __lt__, __gt__, __le__, or __ge__, it will automatically fill in the rest for you.