How to get the least common element in a list? How to get the least common element in a list? python-3.x python-3.x

How to get the least common element in a list?


most_common without any argument returns all the entries, ordered from most common to least.

So to find the least common, just start looking at it from the other end.


What about

least_common = collections.Counter(array).most_common()[-1]


Borrowing the source of collections.Counter.most_common and inverting as appropriate:

from operator import itemgetterimport heapqimport collectionsdef least_common_values(array, to_find=None):    counter = collections.Counter(array)    if to_find is None:        return sorted(counter.items(), key=itemgetter(1), reverse=False)    return heapq.nsmallest(to_find, counter.items(), key=itemgetter(1))>>> data = [1,1,2,2,2,2,3,3,3,3,3,3,3,4,4,4,4,4,4,4]>>> least_common_values(data, 2)[(1, 2), (2, 4)]>>> least_common_values([1,1,2,3,3])[(2, 1), (1, 2), (3, 2)]>>>