# Calculating the mode when the list of numbers may have multiple modes from collections import Counter def calculate_mode(n): c = Counter(n) num_freq = c.most_common() max_count = num_freq[0][1] modes = [] for num in num_freq: if num[1] == max_count: modes.append(num[0]) return modes # Finding the Mode def calculate_mode(n): c = Counter(n) mode = c.most_common(1) return mode[0][0] #src : Doing Math With Python.
Here is what the above code is Doing:
1. We import the Counter class from the collections module.
2. We create a Counter object from the list of numbers.
3. We use the most_common method to get a list of tuples.
4. We get the highest value in the list of tuples.
5. We create a list of the modes.
6. We return the list of modes.