Python – Find the least occurred string in a list

Find the string with least occurrences in list

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

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

min(x, key=x.count)

The min() builtin 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 min() function returns the string element with least number of occurrences in this scenario.

Examples

1. Find least occurred string in list x

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

Python Program

x = ['apple', 'fig', 'mango', 'apple', 'mango']
leastFrequent = min(x, key=x.count)
print(leastFrequent)
Run Code Copy

Output

fig

2. If there are more than one string with least number of occurrences in the list

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

In the following program there are two strings with least number of occurrences in the list: 'fig' and 'banana'. Of these, the first element 'fig' is returned by the min() function.

Python Program

x = ['apple', 'fig', 'mango', 'banana', 'apple', 'mango']
leastFrequent = min(x, key=x.count)
print(leastFrequent)
Run Code Copy

Output

fig

Summary

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

Code copied to clipboard successfully 👍