Syntax
__lt__(self, other)
Example
class Person: def __init__(self, age): self.age = age def __lt__(self, other): return self.age < other.age alice = Person(18) bob = Person(17) carl = Person(18) print(alice < bob) # False print(alice < carl) # False print(bob < alice) # True
Background Video
Default Implementation of __lt__
class Person: def __init__(self, age): self.age = age alice = Person(18) bob = Person(17) carl = Person(18) print(alice < bob)
Traceback (most recent call last): File "C:\Users\...\code.py", line 10, in <module> print(alice < bob) TypeError: '<' not supported between instances of 'Person' and 'Person'
TypeError: ‘<‘ not supported between instances of ‘…’ and ‘…’
class Finxter: pass x = Finxter() y = Finxter() x < y # Python will raise an error!
Traceback (most recent call last): File "C:\Users\...\code.py", line 8, in <module> x < y # Python will raise an error! TypeError: '<' not supported between instances of 'Finxter' and 'Finxter'
class Finxter: def __lt__(self, other): return 42 x = Finxter() y = Finxter() x < y # Now it works! # 42
Commutativity of Less Than <
class Person: def __lt__(self, other): return False class Human: def __lt__(self, other): return True alice = Person() bob = Human() print(alice < bob) # False print(bob < alice) # True

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.