How to find the most repeated number in a list

5

I have the following list:

[0, 1, 2, 3, 4, 6, 6, 17, 16, 9, 10, 23, 12, 13, 14, 15, 16, 17, 18, 4, 20, 4, 22, 23, 24, 4, 4]

I wanted to know how to find the number with the most repetitions without having to use a cycle since I do not see it very practical, especially with very long lists. My idea was to use a dictionary whose elements have those in the list and that here if you check the number with higher repetitions using a for, however it is a process that can be very long but can be effective; and the last idea was to use the count function in the one cycle that reviews each element of the set in the list.

Is there a more effective way to solve this problem? Any ideas?

Thanks!

asked by DDR 29.03.2018 в 19:17
source

9

Good morning you could try it with the statistics library

from statistics import mode
x = [0, 1, 2, 3, 4, 6, 6, 17, 16, 9, 10, 23, 12, 13, 14, 15, 16, 17, 18, 4, 20, 4, 22, 23, 24, 4, 4]
print(mode(x))

# 4

source
4

With Python base, you have some alternatives:

from collections import Counter

lista = [0, 1, 2, 3, 4, 6, 6, 17, 16, 9, 10, 23, 12, 13, 14, 15, 16, 17, 18, 4, 20, 4, 22, 23, 24, 4, 4]

print(Counter(lista).most_common()[0][0])

The Counter() object creates a list of tuples with each element and the number of occurrences, and the method [ most_common()][2] of returns that list sorted by occurrences from highest to lowest.

Another less performant but more compact form of writing is:

print(max(set(lista), key=lista.count))

Here we generate a set which is the set of the unique elements of the list, and we apply a max() using a method of every list the count(elemento) that returns the amount of elemento in the list.

3

One possible solution is to use Counter :

from collections import Counter

l = [0, 1, 2, 3, 4, 6, 6, 17, 16, 9, 10, 23, 12, 13, 14, 15, 16, 17, 18, 4, 20, 4, 22, 23, 24, 4, 4]
c = Counter(l)
print(max(c, key=c.get))

Output:

4