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.
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.
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.
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With