# python sorted function

Sorted function is a great function in my study process and when I learning python, I’ve used it so many times, today, let me conclude some usage of this function.

## sorted function#

### Basics#

Ascending sorting:

the sorted() function accepts any iterable:

### Key functions#

The key parameter to specify a function (or other callable) to be called on each list element prior to making comparisons:

The key should be a function or any callable.

Another examples:

Sort a dict by value:

The same technique works for objects with named attributes. For example:

### Operator Module Function#

The key-function patterns shown above are very common, so Python provides convenience functions to make accessor functions easier and faster. The operator module has itemgetter(), attrgetter(), and a methodcaller() function.

The operator module functions allow multiple levels of sorting. For example, to sort by grade then by age:

You can use reverse=True to flag descending sorts:

### Sort Stability and Complex Sorts#

From Wikipedia, the definition of sorting stability is:

Stable sort algorithms sort equal elements in the same order that they appear in the input.

For example, Stable sorting algorithms choose one of these, according to the following rule: if two items compare as equal, then their relative order will be preserved, i.e. if one comes before the other in the input, it will come before the other in the output.

In Sorted, Sorts are guaranteed to be stable.

Notice how the two records for blue retain their original order so that ('blue', 1) is guaranteed to precede ('blue', 2).

You can 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: