Search code examples
pythonpython-3.xcounter

How to get the least common element in a list?


To find the most common, I know I can use something like this:

most_common = collections.Counter(list).most_common(to_find)

However, I can't seem to find anything comparable, for finding the least common element.

Could I please get recommendations on how to do.


Solution

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

    from operator import itemgetter
    import heapq
    import collections
    def 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)]
    >>>