Python most_common() Function
most_common() function is a method provided by the Counter class in Python's collections module. It returns a list of the n most common elements and their counts from a collection, sorted by frequency. Example:
from collections import Counter
a = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
# create a Counter object
counter = Counter(a)
# elements according to the frequency in decreasing order
res = counter.most_common()
print(res)
Output
[('apple', 3), ('banana', 2), ('orange', 1)]
Syntax of most_common()
most_common(n)
Parameters:
- n (optional): An integer specifying how many of the most common elements to retrieve. Defaults to returning all elements.
Returns: A list of tuples containing the n most common elements and their counts, sorted in descending order by frequency.
Examples of most_common()
Example 1: Finding the Most Common Words in a String
from collections import Counter
s = "Ram and Shyam are friends. Also, Ram and Ghanshyam are college friends. All of them Studies from GeeksforGeeks"
res = Counter(s.split()).most_common(3)
print(res)
Output
[('Ram', 2), ('and', 2), ('are', 2)]
Explanation: The function splits the text into words and counts how many times each word appears. The three most common words are returned along with their counts.
Example 2: Counting Character Occurrences
from collections import Counter
a = "abracadabra"
# Get the most common character and its count
res = Counter(string).most_common(1)
print(res)
Output
[('a', 5)]
Explanation: The function counts the occurrence of each character in the string and returns the most common character ('a') along with its frequency (5 times).
Example 3: Identifying Popular Items in a list
from collections import Counter
a = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
res = Counter(items).most_common(1)
print(res)
Output
[('apple', 3)]
Explanation: The function counts how many times each item appears in the list and returns the most common item ('apple') with its frequency (3 times).
Related Articles: