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?
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?
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())
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()
lst.sort() equal to [1,11,111,2,3,33,333] awesome sort !