Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: value that occurs the most in a list

Tags:

python

list

I have a two list as follows

x = ['a','a','b','c','b','a']

and

x = ['a','a','b','c','c','d']

I'm trying to find which values occur the most in each of these lists. This is what I have tried.

def unique_values(output,input):
    for i in input:
        if i not in output:
            output.append(i)
k = []
for i in k:
    unique_values(k,x)
    y.remove(i)

I've gotten this far but I cant figure out how to stop the for i in k: before it removes all the values in the list.

like image 408
Keenan Avatar asked Dec 04 '12 16:12

Keenan


People also ask

How do I find the most frequent value in a list Python?

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 occurrence of an element in a list?

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 I find the most common number in a list?

If you just want to find most common number in a list, you can use a simple formula. Select a blank cell, here is C1, type this formula =MODE(A1:A13), and then press Enter key to get the most common number in the list.


1 Answers

You can use Counter module from collections, if you want to find the occurrences of each element in the list: -

>>> x = ['a','a','b','c','c','d']

>>> from collections import Counter
>>> count = Counter(x)
>>> count
Counter({'a': 2, 'c': 2, 'b': 1, 'd': 1})
>>> count.most_common()
[('a', 2), ('c', 2), ('b', 1), ('d', 1)]

So, the first two elements are most common in your list.

>>> count.most_common()[0]
('a', 2)
>>> count.most_common()[1]
('c', 2)

or, you also pass parameter to most_common() to specify how many most-common elements you want: -

>>> count.most_common(2)
[('a', 2), ('c', 2)]

Update : -

You can also find out the max count first, and then find total number of elements with that value, and then you can use it as parameter in most_common(): -

>>> freq_list = count.values()
>>> freq_list
[2, 2, 1, 1]
>>> max_cnt = max(freq_list)
>>> total = freq_list.count(max_cnt)

>>> most_common = count.most_common(total)
[('a', 2), ('c', 2)]

>>> [elem[0] for elem in most_common]
['a', 'c']
like image 186
Rohit Jain Avatar answered Oct 06 '22 00:10

Rohit Jain