Skip to content
Advertisement

What functions can be used as ‘key=func’ arguments in the min() and max() functions?

For example:

names = ['Rodrigo', 'Matthew', 'Adam', 'Will']


def get_len(name):
    return len(name)


print(max(names, key=get_len))
print(min(names, key=get_len))
# or
print(max(names, key=lambda name : len(name)))
print(min(names, key=lambda name : len(name)))

How do I know whether it is possible or not possible to use a function as a ‘key=func’ argument?

Advertisement

Answer

As indicated in the documentation, min() (and max()) expect a one-argument ordering function like that used for list.sort(). https://docs.python.org/3/library/functions.html#min

So, what’s expected is a function that takes a single argument from the collection that min() or max() is applied to and that returns a single value that can be ordered with < and >.

So, for names, which is a list of strings, that would be a function that takes a single str as an argument and returns something that is comparable using < or > to order the strings, for example its length.

So, even this would work:

names = ['Rodrigo', 'Matthew', 'Adam', 'Will']

print(max(names, key=len))

To answer your general question “How do I know whether it is possible or not possible to use a function as a key argument to min()?”

You check if the function:

  • accepts a single argument
  • the type of the argument matches the type of the elements of the collection min() will be applied to
  • returns a value that can be ordered using < and >
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement