In this tutorial, you will learn how to find the mode of a list in Python without using any inbuilt functions. The mode of a list is the value that appears most often in the list.
Calculating mode helps you identify the most common item in a dataset, which is a crucial aspect of statistical analysis.
While you can use Python’s statistics library to find the mode, this tutorial will guide you through creating a custom function to calculate the mode manually.
Step 1: Create a Python function
First, let’s create a function named find_mode() which accepts a list as its parameter.
1 2 |
def find_mode(data_list): # Your code here |
Step 2: Calculate the frequency of each element in the list
In this step, we will iterate through the input list and calculate the frequency of each element using a dictionary. The keys of the dictionary will be the unique numbers from the input list, while the values will store the number of occurrences of each number.
1 2 3 4 5 6 7 8 |
def find_mode(data_list): frequency_dict = {} for num in data_list: if num in frequency_dict: frequency_dict[num] += 1 else: frequency_dict[num] = 1 |
Step 3: Find the mode using the maximum frequency
Now that we have the frequency of each element, we can find the mode by iterating through the dictionary and selecting the key(s) with the highest frequency value. If multiple keys have the same maximum frequency, we can store all of them as modes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
def find_mode(data_list): frequency_dict = {} mode_list = [] max_frequency = 0 for num in data_list: if num in frequency_dict: frequency_dict[num] += 1 else: frequency_dict[num] = 1 for key, value in frequency_dict.items(): if value > max_frequency: max_frequency = value mode_list = [key] elif value == max_frequency: mode_list.append(key) return mode_list |
Step 4: Test your function
Let’s test your find_mode() function with an example list.
1 2 3 |
data = [3, 2, 4, 6, 8, 3, 1, 9, 5, 7, 3, 6, 7, 3, 8, 2, 5, 2] mode = find_mode(data) print("Mode:", mode) |
Full code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
def find_mode(data_list): frequency_dict = {} mode_list = [] max_frequency = 0 for num in data_list: if num in frequency_dict: frequency_dict[num] += 1 else: frequency_dict[num] = 1 for key, value in frequency_dict.items(): if value > max_frequency: max_frequency = value mode_list = [key] elif value == max_frequency: mode_list.append(key) return mode_list data = [3, 2, 4, 6, 8, 3, 1, 9, 5, 7, 3, 6, 7, 3, 8, 2, 5, 2] mode = find_mode(data) print("Mode:", mode) |
Output:
Mode: [3]
Conclusion
Now you know how to find the mode of a list in Python without using any inbuilt functions.
This custom function provides you with a deeper understanding of how to determine the mode of a dataset by iterating through each element, using dictionaries to calculate frequencies, and finding the element(s) with the highest frequency.