Sub topic 5
Comparison operators
This chapter assumes you can run Python code and know the built-in types int, float, str, bool, list and tuple. It covers the six operators that compare two values and the rules for which values can be compared.
The six operators
A comparison operator takes two operands and returns a bool.
| Operator | Meaning |
|---|---|
| `==` | equal to |
| `!=` | not equal to |
| `<` | less than |
| `<=` | less than or equal to |
| `>` | greater than |
| `>=` | greater than or equal to |
A single = assigns a value. == tests for equality. Writing if x = 3: is a syntax error, so the mistake is caught early.
Comparing different types
Numbers compare by value across types, so 3 == 3.0 is True. Because bool is a subclass of int, True == 1 is also True.
Ordering comparisons (<, >, <=, >=) between unrelated types raise TypeError. The equality operators do not raise. 1 == "1" is simply False.
print(3 == 3.0)
print(1 == "1")
try:
print(1 < "2")
except TypeError as error:
print(error)The last line prints '<' not supported between instances of 'int' and 'str'.
Strings and sequences
Strings compare by Unicode code point, one character at a time. That is why uppercase letters sort before lowercase ones: "Z" < "a" is True. Lists and tuples use the same lexicographic rule. Python compares the first pair of items. If they differ, that pair decides the result. If they are equal, it moves to the next pair. If one sequence runs out first, the shorter one is smaller.
print("apple" < "banana")
print("Z" < "a")
print((1, 2) < (1, 3))
print([1, 2, 3] < [1, 2])This prints True, True, True and False.
Chaining
Python lets you write 1 < x < 10. It means 1 < x and x < 10, and x is evaluated only once. The next chapters cover chaining in more depth, along with is, which tests identity rather than equality.
Common errors
- Comparing floats with
==.0.1 + 0.2 == 0.3isFalsebecause of binary rounding. Usemath.iscloseinstead. - Sorting mixed types. A list such as
[3, "a"]cannot be sorted, becausesortuses<, which raisesTypeError. - Expecting NaN to equal itself.
float("nan") == float("nan")isFalse. NaN is never equal to anything, including itself.
Exercise
What does print((2, 9) < (3, 0)) output, and why?
Show answer
It prints True. Python compares the first items, 2 and 3. They differ and 2 < 3, so that pair decides the result and the second items are never compared.