Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Python: lt()

📅 2010-Feb-05 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ comparisons, lists, python, sort ⬩ 📚 Archive

If you try to sort a list of objects of your own class …

class Foobar:
    def __init__(self, idx):
        self.idx = idx

fooList = [Foobar(10), Foobar(2)]

… you get a TypeError error:

TypeError: unorderable types: Foobar() < Foobar()

Python is reporting that it does not know how to compare Foobar objects.

Define a __lt__() method in the Foobar class. This rich comparison method is preferred over the generic __cmp__() method.

class Foobar:
    def __lt__(self, other):
    """Less-than comparison."""
    return self.idx < other.idx

© 2023 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘 Mastodon📧 Email