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 using a cycle since I don't see this as very practical, especially with very long lists. My idea was to use a dictionary whose elements have those of the list and here if you check the number with more repetitions through a for, however it is a process that can be very long but can be effective; and the last idea was to use the function count
in a loop that checks each element of the list set.
Is there a more efficient way to solve this problem? Any ideas?
Thank you!
Good morning, could you try it with the statistics library?
With base Python, you have a few alternatives:
The object
Counter()
creates a list of tuples with each element and the number of occurrences, and the [ methodmost_common()][2]
of returns that list sorted by occurrences from highest to lowest.Another less performant but more compact way of writing is:
Here we generate a
set
which is the set of the unique elements of the list, and we apply amax()
using a method of all listcount(elemento)
which returns us the amount ofelemento
in the list.A possible solution is to use
Counter
:Output:
Another option is the "scipy" library.
Advantage: Counts the number of times the number is repeated.
Disadvantage: You have to import numpy which is another module.
a = [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]
moda, count = stats.mode(np.array(a))