Why does Python’s sorted() ignore my custom __lt__ method when sorting a list of objects?

2 weeks ago 13
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?

Read Entire Article