ZetCode

Python __lt__ Method

Last modified November 18, 2026 Python 3.15

The < operator calls __lt__ on its left operand. The method is the main building block for ordering objects: sorted(), min() and list.sort() all rely on it. This article covers the basic dispatch, sorting, mixed types, the reflected method, derived comparisons and reverse ordering.

Basic less-than comparison

A class implements __lt__(self, other) to define when it comes before another object. The example compares products by price.

basic_lt.py
class Product:
    def __init__(self, name, price):
        self.name = name
        self.price = price

    def __lt__(self, other):
        return self.price < other.price

    def __repr__(self):
        return f"Product({self.name}, {self.price})"


laptop = Product("Laptop", 999)
phone = Product("Phone", 699)
print(laptop < phone)
print(phone < laptop)

The cheaper phone comes before the laptop. The hook receives the right operand and returns a boolean; there is no implicit conversion of the other object.

$ python basic_lt.py
False
True

Sorting objects

Python's sorting machinery uses __lt__ for every comparison. Once the hook is defined, a list of objects can be sorted without a key function.

sorting_lt.py
class Student:
    def __init__(self, name, grade):
        self.name = name
        self.grade = grade

    def __lt__(self, other):
        if not isinstance(other, Student):
            return NotImplemented
        return self.grade < other.grade

    def __repr__(self):
        return f"{self.name}:{self.grade}"


students = [Student("Alice", 85), Student("Bob", 72),
            Student("Charlie", 90)]
print(sorted(students))
print(sorted(students, reverse=True))

The students are ordered from the lowest grade to the highest. The reverse argument flips that order without changing the hook. The __repr__ method only makes the result readable.

$ python sorting_lt.py
[Bob:72, Alice:85, Charlie:90]
[Charlie:90, Alice:85, Bob:72]

Mixed types and unit conversion

Comparison can cross types when the hook knows how to interpret the other operand. Here two temperatures are converted to a common scale before being compared, while an unrelated type triggers NotImplemented.

units_lt.py
class Temperature:
    def __init__(self, value, unit="C"):
        self.value = value
        self.unit = unit

    def _celsius(self):
        if self.unit == "C":
            return self.value
        return (self.value - 32) * 5 / 9

    def __lt__(self, other):
        if not isinstance(other, Temperature):
            return NotImplemented
        return self._celsius() < other._celsius()

    def __repr__(self):
        return f"Temperature({self.value}, {self.unit})"


t1 = Temperature(25)
t2 = Temperature(77, "F")
print(t1, t2)
print(t1 < t2, t2 < t1)
try:
    print(t1 < 30)
except TypeError as e:
    print(type(e).__name__, e)

25 degrees Celsius and 77 degrees Fahrenheit are the same temperature, so neither is less than the other. Comparing with a bare integer is not supported and ends in TypeError.

$ python units_lt.py
Temperature(25, C) Temperature(77, F)
False False
TypeError '<' not supported between instances of 'Temperature' and 'int'

The reflected __gt__ method

When the left operand does not recognise the right one, Python tries __gt__ on the right operand with the arguments swapped. Defining it lets a custom object be compared against an unrelated type from either side.

reflected_lt.py
class Proxy:
    def __gt__(self, other):
        print("Proxy.__gt__")
        return "reflected result"


class Left:
    def __init__(self, value):
        self.value = value

    def __lt__(self, other):
        if not isinstance(other, int):
            return NotImplemented
        return self.value < other


print(Left(1) < Proxy())

Left.__lt__ declined the Proxy object, so Python called Proxy.__gt__(Left(1)). The string it returned became the result of the < expression. Python does not force comparison methods to return booleans, though most classes should.

$ python reflected_lt.py
Proxy.__gt__
reflected result

Deriving the other comparisons

With functools.total_ordering you only need __lt__ and __eq__. The decorator supplies <=, > and >= from them.

total_ordering_lt.py
from functools import total_ordering


@total_ordering
class Rectangle:
    def __init__(self, width, height):
        self.area = width * height

    def __lt__(self, other):
        if not isinstance(other, Rectangle):
            return NotImplemented
        return self.area < other.area

    def __eq__(self, other):
        if not isinstance(other, Rectangle):
            return NotImplemented
        return self.area == other.area

    def __repr__(self):
        return f"Rectangle({self.area})"


r1 = Rectangle(3, 4)
r2 = Rectangle(2, 6)
r3 = Rectangle(4, 4)
print(r1 < r2, r1 <= r2)
print(r1 > r3, r1 >= r3)

The first two rectangles both have area 12: < is false but <= is true. Both are smaller in area than the third rectangle, so > and >= are false. The decorator derived all four answers from the two hooks.

$ python total_ordering_lt.py
False True
False False

Reverse ordering

A class can define its own natural order in reverse, or keep the usual hook and let the caller pass reverse=True. Both approaches are shown below.

reverse_lt.py
class NaturalReverse:
    def __init__(self, name, years):
        self.name = name
        self.years = years

    def __lt__(self, other):
        return self.years > other.years

    def __repr__(self):
        return f"{self.name}({self.years})"


class Normal:
    def __init__(self, name, years):
        self.name = name
        self.years = years

    def __lt__(self, other):
        return self.years < other.years

    def __repr__(self):
        return f"{self.name}({self.years})"


a = [NaturalReverse("Alice", 3), NaturalReverse("Bob", 10),
     NaturalReverse("Charlie", 5)]
b = [Normal("Alice", 3), Normal("Bob", 10), Normal("Charlie", 5)]
print(sorted(a))
print(sorted(b, reverse=True))

Both lists end up in the same order. The first class bakes the reversal into __lt__, which affects every sort; the second keeps a normal hook and reverses only at the call site. Prefer the second approach when the class has a genuine natural order.

$ python reverse_lt.py
[Bob(10), Charlie(5), Alice(3)]
[Bob(10), Charlie(5), Alice(3)]

The operator.lt function

operator.lt(a, b) is the functional form of a < b. It dispatches through the same hook and can be used where a callable is required.

operator_lt.py
import operator


class Rank:
    def __init__(self, score):
        self.score = score

    def __lt__(self, other):
        return self.score < other.score

    def __repr__(self):
        return f"Rank({self.score})"


a = Rank(10)
b = Rank(20)
print(operator.lt(a, b))
print(operator.lt(3, 2))

The custom object and the built-in integer both use their own comparison implementations. The results are ordinary booleans that can be stored or passed on.

$ python operator_lt.py
True
False

Best practices

A few rules keep < consistent:

Source

object.__lt__ - Python documentation

Rich comparisons - Python documentation

functools.total_ordering - Python documentation

operator.lt - Python documentation

In this article we have implemented the __lt__ method. We have covered the basic dispatch, sorting, mixed types, reflected comparison, derived comparisons, reverse ordering and operator.lt. For related topics, see Python __le__ method, Python __gt__ method, and Python sorting.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.