1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Why does Python’s sorted() ignore my custom __lt__ method when sorting a list of...

Discussão em 'Python' iniciado por Stack, Novembro 28, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página