Write a Python program to find the frequency of each element in an array
In this post, you will learn how to find the frequency of each element in an array using the Python programming language.
Suppose we have been given an unsorted array. Some elements of the array may be repeated multiple times, and it is tough to get the frequency of each element of the array manually. But, we can easily do this using the Python programming. In this article, we have mentioned different Python programming solutions to count the frequency of each element in an array.
Frequency of each element in array using Dict
Python has an in-built dictionary called dict, which we can use to create an arbitrary definition of the character string. The dict() is a constructor which is used to create instances of the class dict.
In the given Python program, we loop through an array and count the occurrences of each element as a frequency and store them in an initialised dict.
# Array Initialization
arr = [11, 11, 22, 22, 22, 33, 22, 33, 33, 44, 44, 44]
# store frequency of each element
frequency = {}
# iterating over the array elements for frequency
for element in arr:
# checking whether it is in the dict or not
if element in frequency:
# incerementing the frequency count by 1
frequency[element] += 1
else:
# setting the count to 1
frequency[element] = 1
# printing the elements frequencies
for key, value in frequency.items():
print(f"{key}: {value}")
When we execute the above code, it returns the following output-
11: 2
22: 4
33: 3
44: 3
Frequency of each element in array using Collections module
The Collections module in Python is a container which is used to store collections of data, for example, lists, dicts, sets, tuples, etc. First, install the collections module using the following command.
In the given program, we import the collection module and initialise an array with elements. The Python Counter class is part of the Collections module. It is a subclass of the dictionary. It stores elements as dictionary keys, and their counts are stored as dictionary values. By using this, we can get the frequency of each element in an array. Finally, we iterate over the result and print the frequencies.
import collections
# element frequencies using the counter class
def getFrequency(arr):
return collections.Counter(arr)
if __name__ == "__main__":
arr = [10, 9, 10, 8, 8, 9, 11, 10, 8, 11, 11, 8]
freq = getFrequency(arr)
# iterate dictionary and print
# the count of each element
for key, value in freq.items():
print(key, " -> ", value)
Output of the above code-
10 -> 3
9 -> 2
8 -> 4
11 -> 3
Frequency of each element in array using naive method
In the given Python program, we have used the naive approach in which the program checks the frequency of each element in an array. By using the naive method, we have used the for loop to traverse the array and check for the same array element. If it is, then increase the count value.
def getFrequency(arr, len):
for i in range(0, len):
flag = False
count = 0
for j in range(i+1, len):
if arr[i] == arr[j]:
flag = True
break
if flag == True:
continue
for j in range(0, i+1):
if arr[i] == arr[j]:
count += 1
print("{0}: {1}".format(arr[i], count))
# Driver Code
arr = [2, 8, 5, 2, 5, 9, 8, 2]
result = len(arr)
getFrequency(arr, result)
Output of the above code:
5: 2
9: 1
8: 2
2: 3
Frequency of each element in array using while loop
Here, we are using the while loop to check the frequency of each element in an array.
def countFrequency(arr, size):
arr.sort()
# Traverse the sorted array
i = 0
while i < size:
count = 1
while i < size - 1 and arr[i] == arr[i + 1]:
i += 1
count +=1
print("{0}: {1}".format(arr[i], count))
i += 1
# Driver Code
arr = [3, 5, 8, 13, 5, 13, 8, 5]
size = len(arr)
countFrequency(arr, size)
Output of the above code:
3: 1
5: 3
8: 2
13: 2
Related Articles
Python convert dataframe to numpy arrayMultiply each element of a list by a number in Python
2d arrays in Python
Convert Python list to numpy array
Convert array to list Python
Python Numpy Array Shape
Bubble sort program in Python
Remove last element from list Python
Merge sort program in Python
Python email multiple recipients
How to generate QR Code in Python using PyQRCode
Python programs to check Palindrome strings and numbers
CRUD operations in Python using MYSQL Connector
Fibonacci Series Program in Python
Python File Handler - Create, Read, Write, Access, Lock File
Python convert XML to JSON
Python convert xml to dict
Python convert dict to xml