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']