Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How objects are sorted in Python

Tags:

python

sorting

Suppose that I have a list lst of some objects.

What value of an object is used to perform sorted(lst) if key function is not provided? Is it hash or some id?

like image 250
Andrew Fount Avatar asked Sep 22 '26 09:09

Andrew Fount


2 Answers

when no key is provided, sort uses exclusively the < operator, as demonstrated in this example:

class A:
    def __init__(self,a):
        self.a = a
    def __lt__(self,other):
        return self.a < other.a

    def __repr__(self):
        return str(self.a)

lst = [A(12),A(10),A(44)]
print(sorted(lst))

here I get:

[10, 12, 44]

sort used the defined __lt__ (less than) operator internally, only, not equal not superior. Sorting is only performed with < operator.

(commenting the __lt__ operator leads to TypeError: unorderable types: A() < A())

like image 95
Jean-François Fabre Avatar answered Sep 25 '26 00:09

Jean-François Fabre


Python sort()

This method sorts the list in place, using only < comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).

Refer: list.sort()

like image 41
Ani Menon Avatar answered Sep 24 '26 22:09

Ani Menon