How To Use The min(), max(), and sorted() Functions With Any Data Type

Some of Python’s built-in functions take an optional key parameter. What is it, and when should you use it?

Finding the minimum value in a list

Python has a min function, but what if it didn’t? How would you find the minimum value in a list? You would need to loop through the values one by one. Each time you found a new minimum, you would have to replace the previous minimum with the new one. Your code would look something like this:

    # Find the smallest value in "values"
    min = None
    for next_value in values:
        if (min is None) or (next_value < min):
            min = next_value

This works if you want to compare the values directly. But what if you need to compare some property of the values instead of the values themselves? For example, what if you have a list of words (strings) and you want to find the shortest word? Clearly, you need to look at the lengths of the words, not the words themselves.
A value used for comparing things is called a key. In this case, you would use the len function to generate the keys (the lengths) and look for the smallest key instead of the smallest value. Here’s one way to do it:
Implementation note – We generate a list of (key,value) tuples for each value in the original list. The < operator tests tuples by comparing them item by item, starting with the first item. The key must be at position [0] of the tuple for the comparison to work properly.
    word_list = 'it was a dark and stormy night'.split()

    # find the shortest word in "word_list"
    min = None
    for next_value in  [(len(word), word) for word in word_list]:
       if (min is None) or (next_value < min):
         min = next_value
    # strip off the key once we're done
    min = min[1]

This idea of comparing keys is really useful, which brings us back to the min function.

The optional key parameter

The min function takes an optional key parameter which lets you pass in a function for generating the comparison keys. Knowing this fact you can rewrite the last example as

    # find the shortest word in "word_list"
    min(word_list, key=len)

Lambda expressions

Lambda expressions are another way of defining a key function. You can think of a lambda as an inline function which gets defined right at the point you need it.
Here’s another example. Imagine you have a list of (city_name, population) pairs

    cities =[
       ("Smallville", 1000),
        ("Bigtown", 30000)
    ]

and you want to find the city with the smallest population. You could write a separate function and use that as the key

    def population(city):
       return city[1]
    min(cities, key=population)

or you could write a lambda expression right inside the function call

    min(cities, key=lambda city: city[1])

Other functions with a key parameter

There are two other built-in functions that work by comparing values and each of them also takes an optional key parameter
  • max
  • sorted

No comments:

Post a Comment