Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts in Python.
To run the program:
In this Python version, we use the sorted() function along with custom key functions to achieve the same sorting behavior as in the original example. The functools.cmp_to_key() function is used to convert the comparison function to a key function for sorting strings by length.
For sorting the list of Person objects, we use a lambda function as the key, which extracts the age attribute for comparison.
Note that Python’s sorting is stable, meaning that equal elements retain their relative order in the sorted output.