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.
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)]>>>