Search code examples
pythonlistmode

How to find the mode of a list when there are multiple modes - Python


I am trying to find out the mode of a list that works, but when there are multiple modes, an error is returned. How would I fix this error in my code?

I want to make it so that it calculates it like how this would be calculated normally [3, 3, 4, 4] => (3+4)/2 = 3.5 if that is possible.

import statistics

numbers = ['3', '3', '4', '4']
mode = statistics.mode(numbers)
print(f'Mode: {mode}')

this is the error I get: statistics.StatisticsError: no unique mode; found 2 equally common values


Solution

  • You can first use collections.Counter to count the number of occurrences of the elements, then use list comprehension to get the elements of the mode.

    from collections import Counter
    import statistics
    
    result_dict = Counter(numbers)
    
    result = [float(i) for i in result_dict.keys() if result_dict[i] == max(result_dict.values())]
    
    statistics.mean(result)
    3.5