Python most_common() Function
Last Updated :
20 Mar, 2024
The 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:
Here, we are using the most_common() function to arrange elements according to the frequency in decreasing order.
Python3
from collections import Counter
# Sample data
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
# Create a Counter object
counter = Counter(data)
# elements according to the frequency in decreasing order
most_common_elements = counter.most_common()
print(most_common_elements)
Output[('apple', 3), ('banana', 2), ('orange', 1)]
Syntax of Python most_common() Function
most_common(n)
Parameters:
- n: An integer specifying the number of most common elements to retrieve.
Returns:
A list of tuples containing the n most common elements and their counts, sorted in descending order by frequency.
Python most_common() Function Examples
Below are some of the commonly used examples of Python most_common() Function of collections module in Python:
Example 1: Analyzing Word Frequency
In this example, we use most_common() to find the three most common words in a piece of text.
Python3
from collections import Counter
# Sample text
text = "Ram and Shyam are friends. Also, Ram and Ghanshyam are college friends. All of them Studies from GeeksforGeeks"
# Get the three most common words
common_words = Counter(text.split()).most_common(3)
print(common_words)
Output[('Ram', 2), ('and', 2), ('are', 2)]
Example 2: Counting Character Occurrences
Here, we utilize most_common() to identify the most common character and its count in a string.
Python3
from collections import Counter
# Sample string
string = "abracadabra"
# Get the most common character and its count
common_char = Counter(string).most_common(1)
print(common_char)
Example 3: Identifying Popular Items
This example demonstrates using most_common() to determine the most popular item in a list along with its count.
Python3
from collections import Counter
# Sample data
items = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
# Get the most common item and its count
popular_item = Counter(items).most_common(1)
print(popular_item)
Share your thoughts in the comments
Please Login to comment...