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 dict. It covers what the six comparison operators return, how they behave across types, and how your own classes take part in them. Chained comparisons and the is operator have their own chapters, so they appear here only where they affect the rules.
The six operators
A comparison operator takes two operands and produces a bool.
| Operator | Meaning | Example | Result |
|---|---|---|---|
| `==` | equal in value | `3 == 3.0` | `True` |
| `!=` | not equal | `3 != 4` | `True` |
| `<` | less than | `"a" < "b"` | `True` |
| `<=` | less than or equal | `5 <= 5` | `True` |
| `>` | greater than | `2 > 7` | `False` |
| `>=` | greater than or equal | `7 >= 7` | `True` |
== and != ask whether two values are the same. The other four ask about order, and they only work when the types define an order.
print(3 == 3.0)
print(True == 1)
print(True > False)
print(3 == "3")This prints True, True, True and False. bool is a subclass of int, so True equals 1. Different types are usually unequal, but not an error. The int 3 and the float 3.0 are equal because numeric types compare by mathematical value.
Numbers
Python compares an int and a float exactly. It does not first convert the int to a float and lose precision.
print(2**53 + 1 == 9007199254740992.0)
print(0.1 + 0.2 > 0.3)Both lines print False and True respectively. The first is False because the integer 2**53 + 1 is not the same number as the float 2**53. The second is True because 0.1 + 0.2 is slightly above 0.3 in binary floating point. For results of float arithmetic, use math.isclose instead of ==.
Strings and sequences
Strings and sequences compare element by element from the left, like dictionary order. This is called lexicographic ordering. The first position where the items differ decides the result. If one sequence is a prefix of the other, the shorter one is smaller.
print("apple" < "banana")
print("Zebra" < "apple")
print([1, 2, 3] < [1, 2, 4])
print((1, 2) < (1, 2, 0))
print([] < [0])Every line prints True. "Zebra" < "apple" is true because strings compare by Unicode code point, and every uppercase ASCII letter has a lower code point than every lowercase one. For human-friendly sorting, pass a key function:
words = ["banana", "apple", "Cherry"]
print(sorted(words))
print(sorted(words, key=str.casefold))The output is ['Cherry', 'apple', 'banana'] and then ['apple', 'banana', 'Cherry'].
Sets use the ordering operators for subset tests, which is not a total order. {1, 2} <= {1, 2, 3} is True. Two sets can be neither < nor > each other, so {1, 2} < {3} and {1, 2} > {3} are both False.
Mixed types
Equality across types never fails. Ordering across types usually does.
try:
print(3 < "5")
except TypeError as error:
print(error)
print({"a": 1} == {"a": 1})The first part prints '<' not supported between instances of 'int' and 'str'. The second prints True, because dictionaries compare equal when their keys and values match. Dictionaries have no ordering, so {} < {} raises TypeError.
This is why sorted([3, "a"]) fails. Sorting uses < internally, and < does not exist between int and str. Convert the data to one type first.
NaN breaks the rules
float("nan") is the "not a number" value. It is the one common value that is not equal to itself.
nan = float("nan")
print(nan == nan)
print(nan != nan)
print(nan < 1, nan > 1)This prints False, True, then False False. Every ordering comparison with NaN is False, and != is True. To detect NaN, call math.isnan(x). Do not write x == nan, which is always False. NaN also makes sorting unreliable, because the order operators no longer behave consistently.
How Python evaluates a comparison
For a == b, Python calls a.__eq__(b). A method can return NotImplemented to say "I don't know how to compare with that type." Python then tries the reflected operation on the other operand. For ordering, a < b falls back to b > a. If both sides decline, == falls back to comparing object identity, and the ordering operators raise TypeError.
Making your own class comparable
A class gets == for free, but the default compares identity, so two separate objects with the same data are unequal. Define __eq__ to compare by value. For ordering, define __lt__. The functools.total_ordering decorator then fills in <=, > and >= from __eq__ and one ordering method.
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, major, minor):
self.major = major
self.minor = minor
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
return (self.major, self.minor) == (other.major, other.minor)
def __lt__(self, other):
if not isinstance(other, Version):
return NotImplemented
return (self.major, self.minor) < (other.major, other.minor)
print(Version(1, 2) < Version(1, 10))
print(Version(1, 2) >= Version(1, 10))
print(Version(1, 2) == Version(1, 2))
try:
Version(1, 2) > 3
except TypeError as error:
print(error)The output is True, False, True, and then a TypeError message about '>' not supported between instances of 'Version' and 'int'. Comparing the tuples (major, minor) is a common trick: tuples already do lexicographic comparison, so you don't write the logic by hand. Returning NotImplemented, instead of False, lets Python try the other operand and produce a correct error.
Common errors
- Writing
=for==.if x = 3:is aSyntaxError. The walrus form:=is a different operator with a different purpose. - Comparing to
TrueorFalse.if flag == True:is redundant and can misfire. A value like2is truthy but2 == TrueisFalse. Writeif flag:. - Using
isfor values.x is 3tests identity and may give surprising results. Use==for values andisonly forNoneand other singletons. - Float equality.
0.1 + 0.2 == 0.3isFalse. Usemath.isclose. - Ordering mixed types. Data read from files or user input is often
str. Convert it withint()orfloat()before comparing to numbers. - Assuming
a != bisnot a == bfor all types. In Python 3 the default__ne__inverts__eq__, so this holds for ordinary classes. NaN is the notable value where==and<both being false is normal.
Exercise
Predict the output of each line, then explain the one that raises an error: print("10" < "9"), print(10 < 9), print((2, "a") < (2, "b")), print([1, "a"] < [1, 2]).
Show answer
"10" < "9" is True, because strings compare character by character and "1" is less than "9". 10 < 9 is False. (2, "a") < (2, "b") is True: the first items are equal, so the second items decide. [1, "a"] < [1, 2] raises TypeError, because the first items are equal and the next pair, "a" and 2, is a str and an int, which have no ordering.
Exercise
A function returns float("nan") when data is missing. Why does if result == float("nan"): never run its body, and what should you write instead?
Show answer
NaN is not equal to anything, including itself, so result == float("nan") is always False. Use import math and then if math.isnan(result):.