Hello nlong! Welcome to our community!
Functions like max()
, min()
, and sorted()
have a special key
parameter that you can use to specify a function to be called on each element of that list!
This page in the documentation has an example that illustrates this very well:
So yes, the key
parameter is used to pass in the function that you want executed on each of the elements of that list. When you pass in the function this way, youâre passing in the function as an argument inside the max()
function.
The use of a function youâre most familiar with is probably something like the following:
def add_two(x)
return x+2
add_two(2)
Here youâre simply calling the function directly. Youâre passing in an argument and telling the function: âhere, take this integer and do your thingâ.
The main difference when using the key
parameter to pass in a function as an argument is that you use it to tell the âprimaryâ function (i.e. max(), min(), etc): âHere, take this list and take this function to use on elements of that list. And then do your thing.â
Hopefully that clears it up!
To answer your questions more directly:
Precisely. The function (an argument) gets called on each value of the list (the list also being an argument), and only then does the max()/min() function do its job. They key parameter is what makes this possible.
most_comments = max(hn_clean, key=retrieve_num_comments)
In essence, this is whatâs going on:
You call a function, max(), and pass in two arguments - an iterable, and a function you want used on the individual components of said iterable. The key
parameter is what communicates this intention of yours to the max()
function.
As you know, what your function does is it returns the value associated with the 'numComments'
key in each dictionary. After the iteration is performed behind the scenes, the max()
function therefore will end up with a list of several ânumComments'
values. So it finally does its job, and selects the maximum value from that list.
It then returns the element within the original iterable that contained this maximum 'numComments'
value it found.