The documentation doesn't guarantee that. Is there any other place that it is documented?
I'm guessing it might be stable since the sort method on lists is guaranteed to be stable (Notes 9th point: "Starting with Python 2.3, the sort() method is guaranteed to be stable"), and sorted is functionally similar. However, I'm not able to find any definitive source that says so.
Purpose: I need to sort based on a primary key and also a secondary key in cases where the primary key is equal in both records. If sorted() is guaranteed to be stable, I can sort on the secondary key, then sort on the primary key and get the result I need.
PS: To avoid any confusion, I'm using stable in the sense of "a sort is stable if it guarantees not to change the relative order of elements that compare equal".
sort is slightly faster than sorted and consumes around 24% less memory. However, keep in mind that list. sort is only implemented for lists, whereas sorted accepts any iterable.
List. sort() established the convention that sort() sorts the object in place, but a set cannot be sorted in place because sets are unordered.
The easiest way to sort is with the sorted(list) function, which takes a list and returns a new list with those elements in sorted order. The original list is not changed. It's most common to pass a list into the sorted() function, but in fact it can take as input any sort of iterable collection.
Stable and Unstable Sorting Algorithms Several common sorting algorithms are stable by nature, such as Merge Sort, Timsort, Counting Sort, Insertion Sort, and Bubble Sort. Others such as Quicksort, Heapsort and Selection Sort are unstable.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With