Is python's sorted() function guaranteed to be stable?
Yes, the intention of the manual is indeed to guarantee that sorted
is stable and indeed that it uses exactly the same algorithm as the sort
method. I do realize that the docs aren't 100% clear about this identity; doc patches are always happily accepted!
They are stable.
By the way: you sometimes can ignore knowing whether sort and sorted are stable, by combining a multi-pass sort in a single-pass one.
For example, if you want to sort objects based on their last_name
, first_name
attributes, you can do it in one pass:
sorted_list= sorted(
your_sequence_of_items,
key= lambda item: (item.last_name, item.first_name))
taking advantage of tuple comparison.
This answer, as-is, covers the original question. For further sorting-related questions, there is the Python Sorting How-To.