Python Program to find frequency of each element in an Array

April 13, 2022, Learn eTutorial

In this simple python program, we need to find the frequency of an array element It's a list-based python program.

To understand this example, you should have knowledge of the following Python programming topics:

What is an array? How to find the frequency of an element?

Arrays are the set of elements of the same data type accessed using a single name, stored in sequential memory locations. In this basic Python program, we need to check the frequency of each element in an array. For that we have to use nested for loop in python, what we are doing is to count the occurrence of each element. Then increment the count variable if one element is found again. We are doing this checking and incrementing counter inside a for loop to check each element's occurrence.

In this Array program in python, to prevent taking an element count twice, we have to initialize a variable as -1 and make every element visited -1.


STEP 1: Accept and initialize an array with values.

STEP 2: Create an array using the length of the first array using len() in python.

STEP 3: Initialize visited elements variable as -1.

STEP 4: Open the outer for loop from zero to the length of the user array and initialize the count variable to 1 to count each element's occurrence in the array. This for loop will traverse through each element in the array.

STEP 5: use an inner for loop from the next element of the outer loop. With that loop, compare each element with the other elements in the array.

STEP 6: use an if condition to check the first element with the other elements in the array and if that is true the count is incremented by 1

STEP 7: Then, we assign the new array with -1 to stop counting the element again.

STEP 8: Use the if condition to check the new array not equal to -1, if so then assign a new array element with the count.

STEP 9: Display the new array elements which have the count for each element in the first array using a for loop and print statement in python language.

Python Source Code

                                          arr = [1, 2, 8, 3, 2, 2, 2, 5, 1];     
#Array fr for storing count of elements  
fr = [None] * len(arr);    
visited = -1;    
for i in range(0, len(arr)):    
    count = 1;    
    for j in range(i+1, len(arr)):    
        if(arr[i] == arr[j]):    
            count = count + 1;    
            #To avoid counting same element again    
            fr[j] = visited;    
    if(fr[i] != visited):    
        fr[i] = count;    
#Displays the count of times array element is present    
print(" Element | Count");    
for i in range(0, len(fr)):    
    if(fr[i] != visited):    
        print("    " + str(arr[i]) + "    |    " + str(fr[i]));    


Element | Count
1           |         2
2           |         4
8           |         1
3           |         1
5           |         1