Get most common elements in Python - Counter.most_common

To get most common elements in Python, use the most_common in Counter.

from collections import Counter

s = [1, 1, 1, 1, 5, 5, 5]

m = Counter(s).most_common()

for p in m:
    print(p)

# (1, 4)
# (5, 3)

There are four 1 and three 5 in the list, so the most_common() returns the values and occurrences, (1, 4) and (5, 3).

Get the letter occurrence

from collections import Counter

s = 'aaaabbbccd'

m1 = Counter(s).most_common(1)
m2 = Counter(s).most_common(2)
m3 = Counter(s).most_common(3)

print(m1)  # [('a', 4)]
print(m2)  # [('a', 4), ('b', 3)]
print(m3)  # [('a', 4), ('b', 3), ('c', 2)]

The most_common(x) returns x elements as a tuple in order of occurrence.

from collections import Counter

s = 'aaaabbbccd'

m = Counter(s).most_common(3)

for p in m:
    print(p)
    print(type(p))
# ('a', 4)
# <class 'tuple'>
# ('b', 3)
# <class 'tuple'>
# ('c', 2)
# <class 'tuple'>

Comments

Powered by Markdown