Search code examples
pythonmode

How to produce multiple modes in Python?


Basically I just need to figure out how to produce modes (numbers occurring most frequently) from a list in Python, whether or not that list has multiple modes?

Something like this:

def print_mode (thelist):
  counts = {}
  for item in thelist:
    counts [item] = counts.get (item, 0) + 1
  maxcount = 0
  maxitem = None
  for k, v in counts.items ():
    if v > maxcount:
      maxitem = k
      maxcount = v
  if maxcount == 1:
    print "All values only appear once"
  if counts.values().count (maxcount) > 1:
    print "List has multiple modes"
  else:
    print "Mode of list:", maxitem

But instead of returning strings in the "All values only appear once," or "list has multiple modes," I would want it to return the actual integers that it's referencing?


Solution

  • Make a Counter, then pick off the most common elements:

    from collections import Counter
    from itertools import groupby
    
    l = [1,2,3,3,3,4,4,4,5,5,6,6,6]
    
    # group most_common output by frequency
    freqs = groupby(Counter(l).most_common(), lambda x:x[1])
    # pick off the first group (highest frequency)
    print([val for val,count in next(freqs)[1]])
    # prints [3, 4, 6]