-6

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?

New contributor
Vanshat is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
10
  • Your output does not match your code. Please post your real code and the actual output that it produces. Commented yesterday
  • 9
    Who graduated this from SG? I already commented that this is norepro there, it should've been addressed before moving the question to the main site. Commented yesterday
  • 2
    It looks like a single, fairly new, low rep user graduated it. I would have thought graduation would take more than a single vote; especially if there was already a vote to the contrary. Commented yesterday
  • 2
    @STerliakov Look it up? Commented yesterday
  • 1
    @KellyBundy thanks! I missed that "staging ground post" in the edit history is actually a link - I thought the SG history is gone once published. Commented yesterday

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.