Skip to content
Advertisement

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

For example:

JavaScript

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:

JavaScript

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