# Finding the Most Common Element in a List

In statistics, the mode is the number that appears most frequently in a list. It’s used to calculate the median and interquartile range, among other things. It’s also useful for basic data validation, …

Updated November 27, 2023

In statistics, the mode is the number that appears most frequently in a list. It’s used to calculate the median and interquartile range, among other things. It’s also useful for basic data validation, as it helps catch errors when there are several equally common values.

1. Using Counter Class:
from collections import Counter

def find_mode(lst):
data = Counter(lst)
max_count = max(data.values())
mode_vals = [k for k, v in data.items() if v == max_count]

return mode_vals

You can call this function by passing a list as an argument like so:

print(find_mode([1, 2, 3, 4, 5, 2])) # Returns [2]

The Counter class automatically counts the occurrence of each element in the passed list. Then it checks for the maximum occurrence value (max_count), and returns all elements that have this count (mode_vals). This way we find mode(s) of a list.

1. Finding Mode with Sorting:
def find_mode_with_sorting(lst):
lst = sorted(set(lst))  # Remove duplicates and sort the list
counts = {}  # dictionary to hold each element's count in the list

for num in lst:
if num not in counts:
counts[num] = 0
counts[num] += 1

max_count = max(counts.values())  # Find maximum count

mode = [k for k, v in counts.items() if v == max_count]  # find the mode (most common element)

return mode[0]

You can call this function by passing a list as an argument like so:

print(find_mode_with_sorting([1, 2, 3, 4, 5, 2])) # Returns 2

This method works by first sorting the unique elements in the list and then counting their occurrences. It finds the maximum count among all elements (max_count), and finally returns the element that has this count (mode). As it only returns one mode, we return the first element from the returned list to match with Counter method’s behavior.

Remember these methods won’t work correctly if there are no modes in the list, i.e., when all elements occur just once. If you need to handle such cases, you will have to add additional code.