0

I have a problem with working principle of python built-in sorting function. I have person class and it holds two attributes such as name and number. I want to sort it based on name attributes. If two names are equal it should be sorted based on number attribute.

import numpy as np
from functools import total_ordering


@total_ordering
class Person(object):
    def __init__(self, name, number):
        self.name=name
        self.number=number

    def __repr__(self):
        return "{}, {}".format(self.number, self.name)

    def __lt__(self, other):
        return (self.name, self.number) < (other.name, other.number)


customList=[
    Person('object', 99),
    Person('michael', 1),
    Person('theodore', 21),
    Person('amazon', 21),
    Person('life', 42),
    Person('tree', 42)
]

a=sorted(customList)
print(a)

Here, I overwrites __lt__ function. However, still it is not clear how sorted function uses it.

I assume that sorting might work in the following code:

for each element1 in arr:
    for each element2 in arr:
        compare element1 and elements with overwritten __lt__ function

Still, the way how sorted function works is not clear for me.

user3104352
  • 1,100
  • 1
  • 16
  • 34

0 Answers0