Sub topic 3
Comparison operators
This chapter assumes you know Python variables, functions, and if statements. It also assumes you know the built-in types int, float, str, list, tuple, dict, and set. It covers what the six comparison operators do for each of those types, when a comparison raises an error instead of returning a result, and how your own classes take part.
The six operators
Python has six comparison operators.
| Operator | Meaning |
|---|---|
| `==` | equal to |
| `!=` | not equal to |
| `<` | less than |
| `<=` | less than or equal to |
| `>` | greater than |
| `>=` | greater than or equal to |
For built-in types, each one returns a bool. A comparison is an ordinary expression, so you can store its result, return it, or pass it to a function.
a = 7
is_big = a > 5
print(is_big) # True
print(type(is_big)) # <class 'bool'>
print(a == 7.0) # True
print(a != 7) # False
print(a >= 8, a <= 7) # False True== compares values. The identity operator is, which asks whether two names refer to the same object, is covered in a later chapter. Chaining such as 1 < x < 10 is also covered separately.
Numbers
Numeric types compare by mathematical value, even across types. 3 == 3.0 is True, and True == 1 is True because bool is a subclass of int. The standard library types fractions.Fraction and decimal.Decimal also compare exactly with int and float.
from fractions import Fraction
from decimal import Decimal
print(3 == 3.0) # True
print(Fraction(1, 2) == 0.5) # True
print(Decimal("0.5") == 0.5) # True
print(2 < 2.5) # True
print(True == 1, False == 0) # True TrueFloating-point equality
Most decimal fractions cannot be stored exactly as binary floats. Testing floats with == after arithmetic therefore often fails.
import math
print(0.1 + 0.2 == 0.3) # False
print(0.1 + 0.2) # 0.30000000000000004
print(math.isclose(0.1 + 0.2, 0.3)) # Truemath.isclose uses a relative tolerance of 1e-09 by default. If one of the values may be zero, also pass abs_tol, because a relative tolerance never matches zero except against zero itself.
import math
print(math.isclose(1e-12, 0.0)) # False
print(math.isclose(1e-12, 0.0, abs_tol=1e-9)) # TrueStrings
Strings compare lexicographically, character by character, using each character's Unicode code point. Python finds the first position where the strings differ and compares those two characters. If one string is a prefix of the other, the shorter one is smaller.
print("apple" < "banana") # True
print("a" < "ab") # True (prefix is smaller)
print("Zebra" < "apple") # True (ord("Z") == 90, ord("a") == 97)
print("10" < "9") # True (compares "1" with "9")
print(ord("Z"), ord("a")) # 90 97Two consequences follow from this.
- Uppercase letters sort before lowercase ones.
- Strings of digits do not sort numerically.
For case-insensitive comparison, use str.casefold(), which handles more cases than lower(). To order text the way a human reader expects in a given language, use the locale module or a library built for that purpose.
print("Straße".casefold() == "STRASSE".casefold()) # True
print("Straße".lower() == "STRASSE".lower()) # FalseSequences, dicts, and sets
Lists and tuples
Lists and tuples compare element by element, like strings. Python stops at the first pair of elements that differ. Equality also requires the same length.
print([1, 2, 3] < [1, 2, 4]) # True
print((1, 2) < (1, 2, 0)) # True (prefix is smaller)
print([1, 2] == (1, 2)) # False (different types)
print([1, 2] == [1, 2]) # True
print((2, "a") < (10, "a")) # TrueA list never equals a tuple, even with the same items. Tuple comparison is useful for multi-field ordering such as (last_name, first_name). If the elements at some position cannot be ordered against each other, the comparison raises TypeError.
try:
print([1, "a"] < [1, 2])
except TypeError as e:
print("TypeError:", e)
# TypeError: '<' not supported between instances of 'str' and 'int'Dicts
Two dicts are equal if they have the same keys and each key maps to an equal value. Insertion order does not matter for ==. Dicts do not support < or >.
print({"a": 1, "b": 2} == {"b": 2, "a": 1}) # True
try:
{"a": 1} < {"a": 2}
except TypeError as e:
print("TypeError:", e)
# TypeError: '<' not supported between instances of 'dict' and 'dict'Sets
For sets, the ordering operators mean subset and superset. <= is "is a subset of" and < is "is a proper subset of". This is a partial order. Two sets can be unrelated, so a < b, a == b, and a > b can all be False at once.
a = {1, 2}
b = {1, 2, 3}
c = {3, 4}
print(a <= b, a < b, a == b) # True True False
print(a < c, a == c, a > c) # False False FalseBecause of this, sorting a list of sets with sorted gives meaningless results.
When comparison raises TypeError
In Python 3, ordering comparisons (<, <=, >, >=) between unrelated types raise TypeError. Python 2 allowed them. Equality is different: == and != never raise for built-in types. They return False and True for unrelated types.
print(1 == "1") # False
print(1 != "1") # True
try:
1 < "2"
except TypeError as e:
print("TypeError:", e)
# TypeError: '<' not supported between instances of 'int' and 'str'A frequent source of this error is input data. A value read from a file or a form is a string, so compare it only after converting it.
raw = "42"
limit = 100
print(int(raw) < limit) # TrueThe same rule makes sorted([3, "a", 1]) fail. The sort has to compare items, and 3 and "a" cannot be ordered.
How Python evaluates a comparison
Each operator maps to a special method on the left operand.
| Operator | Method |
|---|---|
| `==` | `__eq__` |
| `!=` | `__ne__` |
| `<` | `__lt__` |
| `<=` | `__le__` |
| `>` | `__gt__` |
| `>=` | `__ge__` |
A method can return the special value NotImplemented, which means "I don't know how to compare with that type". Python then tries the reflected operation on the right operand. For example, a < b falls back to b > a, and a == b falls back to b == a. If both sides decline, == falls back to an identity check, and an ordering operator raises TypeError.
Comparisons in your own classes
A class that does not define __eq__ inherits the default, which compares identity. Two separate instances are then never equal. To compare by value, define __eq__. Return NotImplemented for types you do not handle, rather than False, so Python can try the other operand.
class Money:
def __init__(self, cents):
self.cents = cents
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented
return self.cents == other.cents
def __lt__(self, other):
if not isinstance(other, Money):
return NotImplemented
return self.cents < other.cents
print(Money(100) == Money(100)) # True
print(Money(100) == 100) # False
print(Money(50) < Money(100)) # True
print(Money(100) > Money(50)) # True (uses the reflected __lt__)
try:
Money(1) < 5
except TypeError as e:
print("TypeError:", e)
# TypeError: '<' not supported between instances of 'Money' and 'int'Note these details:
Money(100) == 100isFalse. Both sides returnedNotImplemented, so Python compared identity.Money(100) > Money(50)works without a__gt__. Python calls the reflectedMoney(50).__lt__(Money(100)).Money(1) <= Money(1)would raiseTypeError, because neither__le__nor its reflection__ge__exists. Rather than writing all six methods, decorate the class withfunctools.total_orderingand define__eq__plus one ordering method. Adataclass(order=True)also generates them.- A class that defines
__eq__without__hash__becomes unhashable, so it cannot be a dict key or set member. Define__hash__consistently with__eq__if you need that.
The next chapters cover __bool__ and truthiness.
Summary of rules
==compares values, and ordering comparisons need types that know how to order against each other.- Do not test floats for exact equality after arithmetic. Use
math.isclose. - Strings and sequences compare element by element and stop at the first difference.
- Sets use
<and>for subset and superset, which is a partial order. ==between unrelated types isFalse.<between them is aTypeError.
Exercise
What does each of these print, and which line raises an error? (1) print((1, 2, 3) < (1, 3)) (2) print("B" < "a") (3) print({1, 2} < {2, 3}) (4) print([1, 2] == (1, 2)) (5) print([1, 2] < (1, 2))
Show answer
(1) True, because the second elements differ and 2 < 3. (2) True, because "B" has code point 66 and "a" has 97. (3) False, because neither set is a subset of the other. (4) False, because a list never equals a tuple. (5) Raises TypeError: '<' not supported between instances of 'list' and 'tuple', because ordering requires compatible types while == does not.
Exercise
A class Version defines _eq and lt_, both returning NotImplemented for non-Version operands. Version("1.2") <= Version("1.2") raises TypeError. Why, and what are two ways to fix it?
Show answer
Python looks for _le on the left operand, then the reflected ge on the right operand, and the class defines neither. Fix it by defining le explicitly, or by decorating the class with functools.totalordering (which derives the other ordering methods from _eq and lt_). Making the class a dataclass with order=True also works.