Sorting By Functions in Python

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.

from functools import cmp_to_key

def main():
    fruits = ["peach", "banana", "kiwi"]

    # We implement a comparison function for string lengths.
    def len_cmp(a, b):
        return len(a) - len(b)

    # Now we can use the sorted() function with this custom
    # comparison function to sort 'fruits' by name length.
    sorted_fruits = sorted(fruits, key=cmp_to_key(len_cmp))
    print(sorted_fruits)

    # We can use the same technique to sort a list of
    # values that aren't built-in types.
    class Person:
        def __init__(self, name, age):
            self.name = name
            self.age = age
        
        def __repr__(self):
            return f"Person(name='{self.name}', age={self.age})"

    people = [
        Person("Jax", 37),
        Person("TJ", 25),
        Person("Alex", 72),
    ]

    # Sort 'people' by age using the sorted() function.
    sorted_people = sorted(people, key=lambda p: p.age)
    print(sorted_people)

if __name__ == "__main__":
    main()

To run the program:

$ python sorting_by_functions.py
['kiwi', 'peach', 'banana']
[Person(name='TJ', age=25), Person(name='Jax', age=37), Person(name='Alex', age=72)]

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.