Find the item with maximum occurrences in a list

158,240

Solution 1

Here is a defaultdict solution that will work with Python versions 2.5 and above:

from collections import defaultdict

L = [1,2,45,55,5,4,4,4,4,4,4,5456,56,6,7,67]
d = defaultdict(int)
for i in L:
    d[i] += 1
result = max(d.iteritems(), key=lambda x: x[1])
print result
# (4, 6)
# The number 4 occurs 6 times

Note if L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 7, 7, 7, 7, 7, 56, 6, 7, 67] then there are six 4s and six 7s. However, the result will be (4, 6) i.e. six 4s.

Solution 2

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

Solution 3

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.

Solution 4

In your question, you asked for the fastest way to do it. As has been demonstrated repeatedly, particularly with Python, intuition is not a reliable guide: you need to measure.

Here's a simple test of several different implementations:

import sys
from collections import Counter, defaultdict
from itertools import groupby
from operator import itemgetter
from timeit import timeit

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

def max_occurrences_1a(seq=L):
    "dict iteritems"
    c = dict()
    for item in seq:
        c[item] = c.get(item, 0) + 1
    return max(c.iteritems(), key=itemgetter(1))

def max_occurrences_1b(seq=L):
    "dict items"
    c = dict()
    for item in seq:
        c[item] = c.get(item, 0) + 1
    return max(c.items(), key=itemgetter(1))

def max_occurrences_2(seq=L):
    "defaultdict iteritems"
    c = defaultdict(int)
    for item in seq:
        c[item] += 1
    return max(c.iteritems(), key=itemgetter(1))

def max_occurrences_3a(seq=L):
    "sort groupby generator expression"
    return max(((k, sum(1 for i in g)) for k, g in groupby(sorted(seq))), key=itemgetter(1))

def max_occurrences_3b(seq=L):
    "sort groupby list comprehension"
    return max([(k, sum(1 for i in g)) for k, g in groupby(sorted(seq))], key=itemgetter(1))

def max_occurrences_4(seq=L):
    "counter"
    return Counter(L).most_common(1)[0]

versions = [max_occurrences_1a, max_occurrences_1b, max_occurrences_2, max_occurrences_3a, max_occurrences_3b, max_occurrences_4]

print sys.version, "\n"

for vers in versions:
    print vers.__doc__, vers(), timeit(vers, number=20000)

The results on my machine:

2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] 

dict iteritems (4, 6) 0.202214956284
dict items (4, 6) 0.208412885666
defaultdict iteritems (4, 6) 0.221301078796
sort groupby generator expression (4, 6) 0.383440971375
sort groupby list comprehension (4, 6) 0.402786016464
counter (4, 6) 0.564319133759

So it appears that the Counter solution is not the fastest. And, in this case at least, groupby is faster. defaultdict is good but you pay a little bit for its convenience; it's slightly faster to use a regular dict with a get.

What happens if the list is much bigger? Adding L *= 10000 to the test above and reducing the repeat count to 200:

dict iteritems (4, 60000) 10.3451900482
dict items (4, 60000) 10.2988479137
defaultdict iteritems (4, 60000) 5.52838587761
sort groupby generator expression (4, 60000) 11.9538850784
sort groupby list comprehension (4, 60000) 12.1327362061
counter (4, 60000) 14.7495789528

Now defaultdict is the clear winner. So perhaps the cost of the 'get' method and the loss of the inplace add adds up (an examination of the generated code is left as an exercise).

But with the modified test data, the number of unique item values did not change so presumably dict and defaultdict have an advantage there over the other implementations. So what happens if we use the bigger list but substantially increase the number of unique items? Replacing the initialization of L with:

LL = [1,2,45,55,5,4,4,4,4,4,4,5456,56,6,7,67]
L = []
for i in xrange(1,10001):
    L.extend(l * i for l in LL)

dict iteritems (2520, 13) 17.9935798645
dict items (2520, 13) 21.8974409103
defaultdict iteritems (2520, 13) 16.8289561272
sort groupby generator expression (2520, 13) 33.853593111
sort groupby list comprehension (2520, 13) 36.1303369999
counter (2520, 13) 22.626899004

So now Counter is clearly faster than the groupby solutions but still slower than the iteritems versions of dict and defaultdict.

The point of these examples isn't to produce an optimal solution. The point is that there often isn't one optimal general solution. Plus there are other performance criteria. The memory requirements will differ substantially among the solutions and, as the size of the input goes up, memory requirements may become the overriding factor in algorithm selection.

Bottom line: it all depends and you need to measure.

Solution 5

If you're using Python 3.8 or above, you can use either statistics.mode() to return the first mode encountered or statistics.multimode() to return all the modes.

>>> import statistics
>>> data = [1, 2, 2, 3, 3, 4] 
>>> statistics.mode(data)
2
>>> statistics.multimode(data)
[2, 3]

If the list is empty, statistics.mode() throws a statistics.StatisticsError and statistics.multimode() returns an empty list.

Note before Python 3.8, statistics.mode() (introduced in 3.4) would additionally throw a statistics.StatisticsError if there is not exactly one most common value.

Share:
158,240
zubinmehta
Author by

zubinmehta

python. math. ML. NLP.

Updated on May 25, 2021

Comments

  • zubinmehta
    zubinmehta about 3 years

    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.

  • SiggyF
    SiggyF almost 13 years
    See the Counter docs for details.
  • Darren Yin
    Darren Yin almost 13 years
    pretty minor, but itemgetter(1) may be better than lambda x: x[1] construct in terms of both simplicity and speed. e. see docs.python.org/howto/sorting.html#operator-module-functions
  • Asara
    Asara over 6 years
    I would like an explanation how max works together with key=
  • PM 2Ring
    PM 2Ring about 6 years
    That's a little inefficient, since .count has to scan the entire list for each item, making it O(n²).
  • PM 2Ring
    PM 2Ring about 6 years
    Counter is convenient, but it's not known for speed. And when n is relatively small O(n²) can be good enough when you're using a function / method that runs at C speed. But when n is large enough, things can get ugly, as I discuss here.
  • Pat Grady
    Pat Grady almost 6 years
    This is a great answer, exactly what I needed and bonus points for the timings! I was trying to quickly find the outlier class in an output from tensorflow.contrib.factorization.KMeansClustering(). The output for the list(kmeans.predict_cluster_index(input_fn)) is an array with no help functions to access the cluster with the highest occurrences.
  • Suman
    Suman over 5 years
    lst = [[1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 56, 6, 7, 67],[1, 2, 45, 55, 5, 5, 5]] max(lst,key=lst.count) in the above example its returning me first list, however I want result like [[4],[5]]
  • moooeeeep
    moooeeeep over 4 years
    Interestingly, rerunning this today on Python 3.6, it turns out that the counter seems to outperform the other approaches for long lists.
  • aidanmelen
    aidanmelen over 4 years
    a Set data structure will remove duplicates rendering your count irrelevant.
  • Luk
    Luk almost 4 years
    @Chris_Rands: great answer ! I found several approaches to this problem on this website. Approach 2 is almost identical to yours, but they first apply the set() operator to the list. I am wondering why this would work: I mean, I am removing all the duplicates from the list and THEN I am using key=list.count.. it doesn't make sense to me. Do you understand this?
  • Boris Verkhovskiy
    Boris Verkhovskiy over 3 years
    this isn't a "little" inefficient. It's O(n²), i.e. very inefficient. If your array has only unique elements (e.g. lst = list(range(1000))), it iterates over the entire array for every element in the array.
  • Boris Verkhovskiy
    Boris Verkhovskiy over 3 years
    This will raise an IndexError if your list is empty.
  • Brian McCutchon
    Brian McCutchon over 3 years
    You could easily improve the speed by changing it to max(lst, key=set(lst).count).
  • JON
    JON about 3 years
    lst = [1, 1, 1, 1, 4, 3, 3, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 4, 4, 4, 5, 4, 1, 4, 4, 4] as count of 4 and 10 is equal so max(lst,key=lst.count) is giving 4 but i wanted 10, how should modify this? @Chris_Rands
  • Chris_Rands
    Chris_Rands about 3 years
    @JON in the case of a tie you want the highest number? max(lst, key=lambda x: (lst.count(x), x))