Albert G Lieu
Albert G Lieu

Reputation: 911

using custom class/function as key in sorted function

I generally understand how to use a lambda function or another array as a key to sort an array, but have a hard time understanding the following usage of custom class as a key in sorted() function. Could you explain how it works and why the first number printed out is 5 in the output?

class STR(str):
    def __lt__(self, other):
        print(self, other)
        return self + other < other + self

list_ = ['3', '30', '34', '5', '9']
sorted(list_, key=STR, reverse=True)

output:
5 9
34 5
30 34
3 30
3 5
3 34
3 30
['9', '5', '34', '3', '30']

However, the following code does not work well. The output is wrong. Does this mean that sorted by default uses __lt__ rather than __gt__ method? Seeing from the output, __gt__ has never been called otherwise it shall print out (self, other).

class STR(str):
    def __gt__(self, other):
        print(self, other)
        return self + other > other + self

list_ = ['3', '30', '34', '5', '9']
sorted(list_, key=STR, reverse=True)

output:
['9', '5', '34', '30', '3']

Upvotes: 1

Views: 598

Answers (1)

raccoons
raccoons

Reputation: 420

Your custom class in this case is inheriting from str and overloading it's __lt__ method. __lt__() is called when you use the less than operator. When you pass this custom class as the key in sorted(), it first maps your class onto the items in your list and then compares them using <, which calls the overloaded __lt__() method in your custom class. As for why it's comparing '5' first, it's because you specified reverse=True so it starts comparing from the end of the list backwards.

Upvotes: 2

Related Questions