Improving my code

I made this function that calculates the mode of a list. I was just wandering if there were any other ways of finding the mode that are more simpler than what I have done. Also there could be a possibility that my code does’nt work.

def mode(list_in):
    count_dict = {}

    for x in list_in:  #makes a dictionary of the numbers in the list and how frequently they appear.
        if x not in count_dict:
            count_dict[x] = 1
        else:
            count_dict[x] += 1
    count_list = []

    for x in count_dict: #makes a list of the frequencies
        count_list.append(count_dict[x])

    maximum = max(count_list)#finds maximum frequency
    mode = []

    for x in count_dict: #adds the numbers corresponding to the maximum frequency to a list
        if count_dict[x] == maximum:
            mode.append(str(x))

    return ",".join(mode)
1 Like

Recall that a sample can have more than one mode. Your code should allow for that and return a list of modes, if there is more than one.

2 Likes