Finding the Mode of List Items Using the Multimode() Function in Python

Finding the Mode of List Items Using the Multimode() Function in Python

ECX 30 Days of Code

Day 2

Mode of a List

Task

Extend the function from day 1 to also print out the modal element(s) of the input list; i.e., to determine which element occurs the most. If there are multiple elements, return a list containing all.

Discussion

In statistics, a mode depicts the value that has the highest frequency among other data values. In a case where two values have the same maximum frequency, we have a bimodal dataset; while if more than two values are having the same maximum frequency, we consider the dataset to be multimodal.

My Approach

On day one, we removed multiple list items, but in today’s task, we would take note of the mode. First, import the statistics module which would be used for the multimode() function. Next, we create a list, which would serve as the argument when we call the function which checks for the mode. We call the multimode() function in the print() function, which checks for the highest occurring item(s), and its result is printed in a list.

import statistics    # For multimode

# List
ecx_items = ["a", "b", "a", "a", 3, 3, 'b', 2, "hello", 'b']


def set_function(list_items):
    """Takes a list and prints a new list with repetitions removed. Also, prints out the modal value(s)"""
    set_list = set(list_items)

    # Print set
    print(list(set_list))

    # Print mode
    print('The mode(s): ', statistics.multimode(list_items))


# Function call
set_function(ecx_items)

Output

['hello', 2, 3, 'a', 'b']
The mode(s):  ['a', 'b']

Run the code on Replit