Find the string with most occurrences in list


Find the string with most occurrences in list

To find the string element with most number of occurrences in given list in Python, call max() built-in function, with list count() function passed as value for key parameter to max() function.

The syntax to find the most occurred string in the list x

max(x, key=x.count)

The max() function compares the strings in the list x based on the return value from key function, which is the number of occurrences of the string element in the list.

And the max() function returns the string element with most number of occurrences in this scenario.

Examples

1. Find most occurred string in list x

In the following program we take a list of strings in x, and find the string with most number of occurrences in the list using max() function.

Python Program

x = ['apple', 'fig', 'mango', 'apple', 'fig', 'apple']
mostFrequent = max(x, key=x.count)
print(mostFrequent)

Output

apple

2. If there are more than one string with most number of occurrences

If there are more than one string element with most number of occurrences in the list, then the string that appears first in the list is returned by max() function.

In the following program there are two strings with most number of occurrences in the list: 'apple' and 'mango'. The first element 'apple' is returned by the max() function.

Python Program

x = ['apple', 'fig', 'mango', 'apple', 'mango']
mostFrequent = max(x, key=x.count)
print(mostFrequent)

Output

apple

Summary

In this tutorial of Python Examples, we learned how to find the most occurred string in the list using max() builtin function, with the help of examples.