I have a list:
hello = ['1', '1', '2', '1', '2', '2', '7']
I wanted to display the most common element of the list, so I used:
m = max(set(hello), key=hello.count)
However, I realised that there could be two elements of the list that occur the same frequency, like the 1’s and 2’s in the list above. Max only outputs the first instance of a maximum frequency element.
What kind of command could check a list to see if two elements both have the maximum number of instances, and if so, output them both? I am at a loss here.
Using an approach similar to your current, you would first find the maximum count and then look for every item with that count:
Alternatively, you can use the nice
Counterclass, which can be used to efficiently, well, count stuff:Then you can use a list comprehension to get all the items that have the maximum count: