From Python 3 docs :
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 fails (and the list is likely to be on the left in a partially changed state).
Documents do not guarantee any behavior in particular, but items will most likely be left in partial sorting. The sort order in which they were located when the exception occurred, and this order may vary depending on the implementation or, possibly (but unlikely) two subsequent program runs.
If you want to try sorting items without worrying about unsuccessful reordering, you can use the built-in sorted function, which will return a new list and not change the original.
>>> seq = ['b', 'a', 3, 'd', 'c'] >>> try: ... seq = sorted(seq) # if sorted fails, result won't be assigned ... except Exception: # you may only want TypeError ... pass ... >>> seq ['b', 'a', 3, 'd', 'c'] # list unmodified
EDIT: reach out to everyone by saying something like
when he sees two different types, an exception occurs
I know that you probably know that such an expression is a simplification, but I think that not clarity, it will cause confusion.
The following example consists of two classes A and B that support comparison with each other through their respective __lt__ methods. It displays a list mixed from these two types, sorted by list.sort() , and then printed in sorted order without any exceptions:
class A: def __init__(self, value): self.a = value def __lt__(self, other): if isinstance(other, B): return self.a < other.b else: return self.a < other.a def __repr__(self): return repr(self.a) class B: def __init__(self, value): self.b = value def __lt__(self, other): if isinstance(other, A): return self.b < other.a else: return self.b < other.b def __repr__(self): return repr(self.b) seq = [A(10), B(2), A(8), B(16), B(9)] seq.sort() print(seq)
The result of this:
[2, 8, 9, 10, 16]
It doesnβt matter that you understand every detail of this. This is just to illustrate that a list of mixed types can work with list.sort() if all parts are there.