views:

189

answers:

3

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

+4  A: 

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!

Alex Martelli
+1  A: 

The "What's New" docs for Python 2.4 effectively make the point that sorted() first creates a list, then calls sort() on it, providing you with the guarantee you need though not in the "official" docs. You could also just check the source, if you're really concerned.

Edit: included link

Peter Hansen
Could you point to where it says so? It says sorted() "works like the in-place list.sort()" and "a newly formed copy is sorted", but I don't see it saying that it internally uses sort().
sundar
The "copy" that is formed is a list (that's what you get as a return value), and .sort() is called on that list prior to returning. QED. No, it's not an unassailable proof, but until Python has an official standard you won't get that.
Peter Hansen
+1  A: 

You don't need to know if sort and sorted are stable, because you don't need to sort in two steps when having multiple keys.

For example, if you want to sort objects based on their last_name, first_name attributes, you can:

sorted_list= sorted(
    your_sequence_of_items,
    key= lambda item: (item.last_name, item.first_name))

taking advantage of tuple comparison.

ΤΖΩΤΖΙΟΥ