How to use user-defined Function In Python

Here we are not using any predefines functions for getting mode of a series. Let us see an example with demonstrates how to calculate mode without predefined functions.

Example :

Python3




# creating a list
lst = [1, 2, 3, 4, 5, 6, 2, 3, 4, 5, 5, 5, 5]
 
# defining a function to calculate mode. It
# takes list variable as argument
def mode(lst):
     
    # creating a dictionary
    freq = {}
    for i in lst:
       
        # mapping each value of list to a
        # dictionary
        freq.setdefault(i, 0)
        freq[i] += 1
         
    # finding maximum value of dictionary
    hf = max(freq.values())
     
    # creating an empty list
    hflst = []
     
    # using for loop we are checking for most
    # repeated value
    for i, j in freq.items():
        if j == hf:
            hflst.append(i)
             
    # returning the result
    return hflst
 
# calling mode() function and passing list
# as argument
print(mode(lst))


Output :

[5]


How to Calculate the Mode of NumPy Array?

In this article, we will discuss how to calculate the mode of the Numpy Array.

Mode refers to the most repeating element in the array. We can find the mode from the NumPy array by using the following methods.

Similar Reads

Method 1: Using scipy.stats package

Let us see the syntax of the mode() function...

Method 2: Using Statistics module

...

Method 3: Using user-defined Function

...