Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the item with maximum occurrences in a list [duplicate]

In Python, I have a list:

L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67]   

I want to identify the item that occurred the highest number of times. I am able to solve it but I need the fastest way to do so. I know there is a nice Pythonic answer to this.

like image 776
zubinmehta Avatar asked Aug 08 '11 19:08

zubinmehta


People also ask

How do you find the maximum occurrence of an element in a list?

Python3. Make use of Python Counter which returns count of each element in the list. Thus, we simply find the most common element by using most_common() method.

How do you find the maximum number of occurrences in Python?

Given a list, the task is to find the number of occurrences of the largest element of the list. Method 1: The naive approach is to find the largest element present in the list using max(list) function, then iterating through the list using a for loop and find the frequency of the largest element in the list.

How do you count the number of repeated elements in a list in Python?

Operator. countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. It returns the Count of a number of occurrences of value.


2 Answers

I am surprised no-one has mentioned the simplest solution,max() with the key list.count:

max(lst,key=lst.count) 

Example:

>>> lst = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67] >>> max(lst,key=lst.count) 4 

This works in Python 3 or 2, but note that it only returns the most frequent item and not also the frequency. Also, in the case of a draw (i.e. joint most frequent item) only a single item is returned.

Although the time complexity of using max() is worse than using Counter.most_common(1) as PM 2Ring comments, the approach benefits from a rapid C implementation and I find this approach is fastest for short lists but slower for larger ones (Python 3.6 timings shown in IPython 5.3):

In [1]: from collections import Counter    ...:     ...: def f1(lst):    ...:     return max(lst, key = lst.count)    ...:     ...: def f2(lst):    ...:     return Counter(lst).most_common(1)    ...:     ...: lst0 = [1,2,3,4,3]    ...: lst1 = lst0[:] * 100    ...:   In [2]: %timeit -n 10 f1(lst0) 10 loops, best of 3: 3.32 us per loop  In [3]: %timeit -n 10 f2(lst0) 10 loops, best of 3: 26 us per loop  In [4]: %timeit -n 10 f1(lst1) 10 loops, best of 3: 4.04 ms per loop  In [5]: %timeit -n 10 f2(lst1) 10 loops, best of 3: 75.6 us per loop 
like image 70
Chris_Rands Avatar answered Sep 22 '22 06:09

Chris_Rands


from collections import Counter most_common,num_most_common = Counter(L).most_common(1)[0] # 4, 6 times 

For older Python versions (< 2.7), you can use this recipe to create the Counter class.

like image 21
phihag Avatar answered Sep 24 '22 06:09

phihag