3

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?

1
  • it depends on the object type. This is described in their respective classes (how they implement comparison). Commented Jan 25, 2018 at 9:42

2 Answers 2

9

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())

Sign up to request clarification or add additional context in comments.

Comments

3

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()

1 Comment

lst.sort() equal to [1,11,111,2,3,33,333] awesome sort !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.