__lt__Easy Examples

Defines behavior for the < less-than operator

Implementing __lt__

Basic implementation of __lt__ in a class.

python
class Student:
    def __init__(self, name, gpa):
        self.name = name
        self.gpa = gpa

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

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

students = [Student("Alice", 3.8), Student("Bob", 3.5), Student("Charlie", 3.9)]
print(sorted(students))

__lt__ defines behavior for the < less-than operator. Implementing it lets you customize how Python interacts with your objects.

__lt__ in action

Seeing __lt__ called by Python's built-in operations.

python
# How Python calls __lt__ automatically
class Demo:
    def __init__(self, value):
        self.value = value

    def __lt__(self, other):
        print(f"__lt__ was called!")
        return self

d = Demo(42)
# This triggers __lt__:
print(d < Demo(100))

Python automatically calls __lt__ when you use the corresponding operator or function on your object.

Want to try these examples interactively?

Open Easy Playground