In this article, we will discuss different ways to get the least common element in a Python List.
Table Of Contents
Get Least Common Value in List
Import Counter class from collections module. The Counter class is a Dictionay subclass, and it is used for counting hashable items. Inside a Counter object, elements are stored as dictionary keys and their counts are stored as dictionary values. We can pass the list object to Counter() function, to get a Counter object. It will have all the unique elements of list as keys, and thier occurrence count as values.
Then call the most_common(n) function of Counter. It returns a list of the n most common elements and their counts from the Counter object. If n is not provided, then it returns all the unique elements in list, and their occurrence count in a decreading order of occurrence count. The last value in this list is the least common value, and its occurrence count. Let’s see an example,
from collections import Counter listOfNums = [11, 15, 12, 11, 15, 16, 12, 11, 19, 15, 19, 16, 11, 12, 16, 12, 15] # Get least common value, and its occurrence count leastCommonValue , frequency = Counter(listOfNums).most_common()[-1] print('Least Common Value : ', leastCommonValue) print('Occurrence Count of Least Common Value : ', frequency)
Least Common Value : 19 Occurrence Count of Least Common Value : 2
The last common element in list was 19, with occurrence
Get N Least Common Values in List
To get the N least common values from a list, we need to pass the select the last N elements from list returned by most_common(). Let’s see an example,
from collections import Counter listOfNums = [11, 15, 12, 11, 15, 16, 12, 11, 19, 15, 19, 16, 11, 12, 16, 12, 15] # Get two least common values in list values = Counter(listOfNums).most_common()[-2 : ] for (value , frequency )in values: print('Value : ', value, ' :: Occurrence Count : ', frequency)
Value : 16 :: Occurrence Count : 3 Value : 19 :: Occurrence Count : 2
We printed the two least common elements of list, along with thier occurrence count.
We learned how to get the least common value in a list in Python.