Find Frequency of each element in an unsorted array in Python

In this tutorial, we are going to learn how to find the frequency of each element in an unsorted array in Python. For finding frequencies dictionaries can be used.

You can check: Dictionary in Python

Finding frequencies of elements

The idea is as follows:

  • First, initialize an empty dictionary.
  • Dictionaries contain a pair of values known as key: value.
  • Here the key is the element and value is its frequency.
  • For each element in the list
    • increase its corresponding value in the dictionary.
  • Finally, print keys and their corresponding values;

Here is the code:

from collections import defaultdict
a=[5,4,1,7,15,5,1,7,7,4,15]
d=defaultdict(int)
for i in a:
    d[i]+=1
for i in d:
    print("element: "+str(i)+"  "+"frequency:"+str(d[i]))
Output:
element: 5 frequency:2
element: 4 frequency:2
element: 1 frequency:2
element: 7 frequency:3
element: 15 frequency:2

We can also find frequencies using the Counter function in python. Here is the code:

from collections import Counter
a=[5,4,1,7,15,5,1,7,7,4,15]
d=Counter(a)
for i in d:
    print("element: "+str(i)+"  "+"frequency:"+str(d[i]))

The above two methods will also work for sorted arrays too.

Leave a Reply

Your email address will not be published. Required fields are marked *