-9

I need a function that returns the most common values from a list. If there is more than one most common value, return all of them.

l = [1, 1, 2, 2, 4]

def most_common(l):
    #some code 
    return common

This should return:

[1, 2]

Since they both appear twice.

I am surprised there is no simple function for this. I have tried collections but can't seem to figure this out.

kevin
  • 11
  • 2

1 Answers1

1

You could first group items in a collections.defaultdict with counts as the values:

from collections import defaultdict

l = [1, 1, 2, 2, 4]

counts = defaultdict(int)
for number in l:
    counts[number] += 1

print(counts)
# defaultdict(<class 'int'>, {1: 2, 2: 2, 4: 1})

Then you could find the most common values from this dictionary:

most_common = [k for k, v in counts.items() if v == max(counts.values())]

print(most_common)
# [1, 2]
RoadRunner
  • 25,803
  • 6
  • 42
  • 75