ARTICLE AD BOX
I have a custom class in Python where I define __lt__ so that objects can be compared.
But when I try to sort a list of these objects, the ordering doesn’t follow my comparison logic.
Here is a minimal reproducible example:
class Item: def __init__(self, value): self.value = value def __lt__(self, other): print("Comparing", self.value, "and", other.value) return self.value > other.value # reverse sorting items = [Item(1), Item(3), Item(2)] sorted_items = sorted(items) print([i.value for i in sorted_items]) Output: [1, 2, 3]This is ascending order, but my __lt__ should have reversed it.
Why is Python ignoring my custom comparison method, and how can I make it respect it?
