Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is python's sorted() function guaranteed to be stable?

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".

like image 636
Sundar R Avatar asked Dec 16 '09 15:12

Sundar R


People also ask

Which is more efficient sort () or sorted ()?

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.

Is set in Python always sorted?

List. sort() established the convention that sort() sorts the object in place, but a set cannot be sorted in place because sets are unordered.

What does sorted function do in Python?

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.

Which sorting method is not stable?

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.


2 Answers

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!

like image 150
Alex Martelli Avatar answered Sep 17 '22 00:09

Alex Martelli


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.

like image 40
tzot Avatar answered Sep 20 '22 00:09

tzot