Python – Find element with least number of occurrences in the list

Find element with least number of occurrences in list

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

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

min(x, key=x.count)
Run

The min() function compares the elements in the list x based on the return value from key function, which is the number of occurrences of an element in the list.

And in this use case, the min() function returns the element with least number of occurrences.

Examples

1. Find least occurred element in list x

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

Python Program

x = [2, 4, 0, 2, 8, 4, 2, 10, 0]
leastFrequent = min(x, key=x.count)
print(leastFrequent)
Run

Output

8

The elements 8 and 10 has occurred only once, and since 8 is the element that appears first in the list, 8 is returned by min().

Summary

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