Karthikeyan Singaravelan <tir.kar...@gmail.com> added the comment:

@Serhiy I just checked the docs to add an example and it's explained with an 
example at [0] :)


```

Sorts are guaranteed to be stable. That means that when multiple records have 
the same key, their original order is preserved.

This wonderful property lets you build complex sorts in a series of sorting 
steps. For example, to sort the student data by descending grade and then 
ascending age, do the age sort first and then sort again using grade:

>>> s = sorted(student_objects, key=attrgetter('age'))     # sort on secondary 
>>> key
>>> sorted(s, key=attrgetter('grade'), reverse=True)       # now sort on 
>>> primary key, descending
[('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

The Timsort algorithm used in Python does multiple sorts efficiently because it 
can take advantage of any ordering already present in a dataset.

```

As noted TimSort makes this efficient by taking advantage of the sorting in the 
first run though it was not done as a single pass. If I am bench marking 
correctly in the attached file then for a list with 400 items using multiple 
pass sort is 4-5x faster than the suggested sorting in Python 3.7 and also more 
readable (though my lambda call is messy :)

Multiple pass sort :
3.871509724
Suggested sort :
17.237952677


[0] 
https://docs.python.org/3/howto/sorting.html#sort-stability-and-complex-sorts

----------
Added file: https://bugs.python.org/file47874/bpo35010_1.py

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue35010>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to