Python program to Sort elements by frequency

In this tutorial, we are going to sort elements in a list by their frequencies. To do this problem we have to first find the frequencies of elements. We can use dictionaries for finding the frequencies of elements.

Sort elements by frequency

The idea is as follows:

  • Find frequencies of elements using a dictionary
  • Initialize a list to be empty.
  • Now for every item in the dictionary
    • append value and key as a single item into the list.
  • Sort the list in increasing order.
  • If two elements have the same frequency then an element with a lesser value will be considered as small.

Here is the code:

from collections import defaultdict
a=[1,1,1,1,2,3,3,4,4]
d=defaultdict(int)
ans=[]
for i in a:
    d[i]+=1
for i in a:
    ans.append([d[i],i])
ans.sort()
for i in range(len(ans)):
    print(ans[i][1],end=" ")
print()
Output:
2 3 3 4 4 1 1 1 1

The frequencies of the elements can also be found easily by Python’s inbuilt Counter function.

Here is the code using the Counter function:

from collections import Counter 
a=[1,1,1,1,2,3,3,4,4] 
d=Counter(a)
ans=[] 
for i in a: 
    ans.append([d[i],i]) 
ans.sort() 
for i in range(len(ans)): 
    print(ans[i][1],end=" ") 
print()
Output:
2 3 3 4 4 1 1 1 1

The output is the same here. The Counter function works the same as the first approach shown here. These are the two ways in which we can sort the elements based on their frequencies. The time complexity is the same in the above two methods.

Leave a Reply

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