so pretty straight through idea, just want to find the most frequent element but I am just lost on exactly what is happening in this small code snippet. I like how this code doesn't import anything, just simply uses the built-ins. But I dont understand exactly how it works. Here it is:
def most_frequent(List):
return max(set(List), key = List.count)
w3schools defines the python max() as doing the following:
The max() function returns the item with the highest value, or the item with the highest value in an iterable. If the values are strings, an alphabetically comparison is done.
Makes sense so far, so if we have a list like so a_list = [3,2,5,1], then max(a_list) gives us 5. Okay, simple enough.
But in our function why is set being used here? I understand set is a built-in data structure that ensures all data inside it to be unique. And what is key? why are there two parameters here inside like this inside the max()? I've never seen anything like this before. Running something like max(4,2,6,3,2) makes sense but putting the data structure set to enclose the list and assigning something called key and calling count on the list? What in the world is going on here? Can someone please break this down like I am five and explain how we are able to use the max() like this when the definition is just to find the highest value? What is set and key doing here? Is it like a hashtable? Quite lost here would truly appreciate the help.
Thank you