If I have a list named as dataset, then I use max(dataset, key = dataset.count) to find the mode. Can someone tell me how max(dataset, key = dataset.count) works? It would be of great help!
1 Answer
The key argument tells the max function which max should be used. Default it will use the values of the elements itself.
dataset = [1, 1, 2, 2, 3, 4, 5, 6, 2, 1, 9, 2, 3, 2, 2, 2]
max(dataset) # 9, since 9 is the max value in this dataset
max(dataset, key=dataset.count) # 2 since 2 occurs the most in this dataset
# You can also use this:
sorted(dataset, key=dataset.count)
# [4, 5, 6, 9, 3, 3, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]
In the last example all elements are sorted from low to high based on the count (how often is the value in the dataset).