pythonlist

How to find several most frequent elements in a list


My program below does find the most frequent element in a list:

numbers = [7, 1, 7, 9, 2, 9, 7, 3, 0]
counter = []

for num in range(10):
    n = numbers.count(num)
    counter.append(n)

largest = max(counter)
print(counter.index(largest))

Output is 7 which is correct.

However, if I add another 9 to the list:

numbers = [7, 1, 7, 9, 2, 9, 7, 3, 0, 9]

which means there are two most frequent elements in a list (in this case, both 7 and 9 are found three times there, as shown above), it only prints one of them - 7 in this case.

Is there any way how to change my code, so that the output will be correct?


Solution

  • Here is a solution that works for any kind of data, not only for positive integers in a range known beforehand.

    We count using a collections.Counter, extract the maximum count which is the count of the most_common number, then make a list of the numbers who have the same count:

    from collections import Counter
    
    numbers = [7, 1, 7, 9, 2, 9, 7, 3, 0, 9]
    counts = Counter(numbers)
    max_count = counts.most_common(1)[0][1]
    out = [value for value, count in counts.most_common() if count == max_count]
    print(out)
    # [7, 9]