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:

1 | sorted([5, 2, 3, 1, 4]) |

the `sorted()`

function accepts any iterable:

1 | 1: 'D', 2: 'B', 3: 'B', 4: 'E', 5: 'A'}) sorted({ |

### Key functions#

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

1 | "This is a test string from Andrew".split(), key=str.lower) sorted( |

The key should be a function or any callable.

Another examples:

1 | student_tuples = [ |

Sort a dict by value:

1 | x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0} |

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

1 | class Student: |

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

1 | from operator import itemgetter, attrgetter |

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

1 | 1,2)) sorted(student_tuples, key=itemgetter( |

You can use `reverse=True`

to flag descending sorts:

1 | 2), reverse=True) sorted(student_tuples, key=itemgetter( |

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

1 | 'red', 1), ('blue', 1), ('red', 2), ('blue', 2)] data = [( |

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*:

1 | 'age')) # sort on secondary key s = sorted(student_objects, key=attrgetter( |