Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Counting maximum occurences of an item in a list with ties allowed

Tags:

python

list

max

Right now I am using the classic counting of occurences in a list max(lst,key=lst.count) but if there is a tie in the maximum occurences of two different elements e.g lst = [1,1,2,2], max returns only one element. In our example it will return 1 or 2 . But I need a function which will return both 1 and 2.


1 Answers

Build a Counter from the list and take the items that match the highest count using a list comprehension:

from collections import Counter

lst = [1,1,2,2]

c = Counter(lst)
maximums = [x for x in c if c[x] == c.most_common(1)[0][1]]
print(maximums)
# [1, 2]

The Counter approach take counts in one pass (O(n)) whereas the list.count approach has O(n^2) time complexity as it passes through the list with each call.

like image 69
Moses Koledoye Avatar answered Oct 27 '25 02:10

Moses Koledoye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!