So I was solving a problem and I found out sort is not stable-sort if key is not provided it will sort according to the second element if key is not provided
but according to documentation its always stable sort:
The sort()
method is guaranteed to be stable. A sort is stable if it guarantees not to change the relative order of elements that compare equal — this is helpful for sorting in multiple passes (for example, sort by department, then by salary grade).
code:
events = [(2, -1), (2, 1), (3, -1), (3, 1), (3, -1)]
events.sort()
print(events)
data = [('red', 1), ('blue', 2), ('red', 2), ('blue', 1)]
data.sort()
print(data)
data = [('red', 1), ('blue', 2), ('red', 2), ('blue', 1)]
data.sort(key=lambda x: x[0])
print(data)
output:
[(2, -1), (2, 1), (3, -1), (3, -1), (3, 1)]
[('blue', 1), ('blue', 2), ('red', 1), ('red', 2)]
[('blue', 2), ('blue', 1), ('red', 1), ('red', 2)]
so it will be stable sort only if i provied a key i didn’t know that. it’s not even mentioned in the documentation. It’s a feature if everyone knows that but it a bug for now
My Python version is:
Python 3.11.4