Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 680
jimy Avatar asked Jan 20 '11 02:01

jimy


People also ask

How do I find the most common number in a list Python?

Make use of Python Counter which returns count of each element in the list. Thus, we simply find the most common element by using most_common() method.

How does counter work in Python?

Counter is a subclass of dict that's specially designed for counting hashable objects in Python. It's a dictionary that stores objects as keys and counts as values. To count with Counter , you typically provide a sequence or iterable of hashable objects as an argument to the class's constructor.


2 Answers

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.

like image 123
Anon. Avatar answered Sep 19 '22 06:09

Anon.


What about

least_common = collections.Counter(array).most_common()[-1] 
like image 39
Jim Brissom Avatar answered Sep 20 '22 06:09

Jim Brissom