How to Make Custom Class Sortable in Python: Simple Guide
To make a custom class sortable in Python, define the
__lt__ method to specify how objects compare using the less-than operator. Optionally, implement other comparison methods like __eq__ for full sorting support. Then, you can use built-in functions like sorted() on your class instances.Syntax
Define the __lt__(self, other) method in your class to tell Python how to compare two objects using the less-than operator (<). This method should return True if self is considered smaller than other, otherwise False.
Optionally, define __eq__(self, other) to specify when two objects are equal. This helps sorting functions handle ties properly.
python
class MyClass: def __init__(self, value): self.value = value def __lt__(self, other): return self.value < other.value def __eq__(self, other): return self.value == other.value
Example
This example shows a custom class Person with an age attribute. We define __lt__ and __eq__ so that sorting a list of Person objects sorts them by age.
python
class Person: def __init__(self, name, age): self.name = name self.age = age def __lt__(self, other): return self.age < other.age def __eq__(self, other): return self.age == other.age def __repr__(self): return f"Person({self.name}, {self.age})" people = [Person("Alice", 30), Person("Bob", 25), Person("Charlie", 35)] sorted_people = sorted(people) print(sorted_people)
Output
[Person(Bob, 25), Person(Alice, 30), Person(Charlie, 35)]
Common Pitfalls
- Not defining
__lt__causesTypeErrorwhen sorting your objects. - Defining only
__lt__without__eq__can cause unexpected behavior in some sorting or comparison operations. - Comparing incompatible types inside
__lt__can raise errors; always check the type ofotherif needed.
python
class Wrong: def __init__(self, value): self.value = value # Missing __lt__ method items = [Wrong(1), Wrong(2)] # This will raise TypeError: # sorted(items) # Correct way: class Right: def __init__(self, value): self.value = value def __lt__(self, other): return self.value < other.value items = [Right(1), Right(2)] print(sorted(items))
Output
[<__main__.Right object at 0x...>, <__main__.Right object at 0x...>]
Quick Reference
To make a class sortable:
- Define
__lt__(self, other)to compare objects. - Optionally define
__eq__(self, other)for equality checks. - Use
sorted()or.sort()on lists of your objects.
Remember: __lt__ means "less than" and controls sorting order.
Key Takeaways
Define __lt__ method in your class to enable sorting by specifying less-than comparison.
Implement __eq__ method to support equality checks and improve sorting behavior.
Use built-in sorted() or list.sort() to sort your custom objects once comparison methods are defined.
Avoid TypeError by ensuring comparison methods handle only compatible types.
Without __lt__, Python cannot sort your custom objects and will raise errors.