0

Let's say I have a python list:

foo = ['A', 'A', 'A', 'B', 'C', 'C']

How would I be able to extract the "least occurring" elements in the list?

Finding the majority elements is easier, doing the following:

print(max(foo, key=foo.count))
'A'

However, how could I efficiently find the least occurring? In the above example, it's 'B'.

In terms of lists whereby all counts are the same, e.g. ['A', 'B', 'C', 'D'], I think all items are "least occurring".

EB2127
  • 1,788
  • 3
  • 22
  • 43

2 Answers2

2

Replace max with min and it will do your work.

Try this :

foo = ['A', 'A', 'A', 'B', 'C', 'C']

print(min(foo, key=foo.count))

>>>'B'

If you have multiple elements with least count same, you can use collections.Counter with dictionary.

Try this :

import collections

foo = ['A', 'B', 'C']

occurrences = collections.Counter(foo)

res =  [key for key in occurrences if all(occurrences[temp] >= occurrences[key] for temp in occurrences)] 

print(res)

>>>['A', 'B', 'c']
Prashant Kumar
  • 2,057
  • 2
  • 9
  • 22
1

Use a Counter to obtain all counts in one iteration:

from collections import Counter

foo = ['A', 'A', 'A', 'B', 'C', 'C']

c = Counter(foo)
m = min(c.values())
mins = [x for x in foo if c[x] == m]
user2390182
  • 72,016
  • 6
  • 67
  • 89