Open In App

Sort List Elements by Frequency – Python

Last Updated : 12 Feb, 2025
Comments
Improve
Suggest changes
6 Likes
Like
Report

Our task is to sort the list based on the frequency of each element. In this sorting process, elements that appear more frequently will be placed before those with lower frequency. For example, if we have: a = [“Aryan”, “Harsh”, “Aryan”, “Kunal”, “Harsh”, “Aryan”] then the output should be: [‘Aryan’, ‘Aryan’, ‘Aryan’, ‘Harsh’, ‘Harsh’, ‘Kunal’] because “Aryan” occurs three times, “Harsh” occurs twice, and “Kunal” occurs once.

Using sorted() with collections.Counter 

We use collections.Counter to count the frequency of each element and then sort the list a based on the negative frequency (to get descending order) using sorted().


Output
['Aryan', 'Aryan', 'Aryan', 'Harsh', 'Harsh', 'Kunal']

Explanation: Counter object computes the frequency of each element in a and sorted() function sorts a using a lambda that returns the negative frequency of each element ensuring elements with higher counts come first.

Using Counter.most_common() with List Comprehension 

In this method we use Counter.most_common() to retrieve elements sorted by frequency and then rebuild the list by repeating each element according to its count.


Output
['Aryan', 'Aryan', 'Aryan', 'Harsh', 'Harsh', 'Kunal']

Explanation:

  • freq.most_common() returns a list of tuples, each containing an element and its count sorted from the highest to the lowest frequency.
  • The loop iterates over these tuples and for each, [item] * count creates a list with the element repeated as many times as it appears.
  • extend() method adds these repeated elements to the result list in order.

Using Naive Approach

We manually count the frequency of each element using a dictionary, sort the dictionary keys by their frequency in descending order and then reconstruct the sorted list.


Output
['Aryan', 'Aryan', 'Aryan', 'Harsh', 'Harsh', 'Kunal']

Explanation:

  • dictionary freq is built by iterating over a and counting each element.
  • The keys of freq are sorted in descending order based on their frequency using sorted() with the reverse=True flag.
  • Result list is then built by repeating each key (element) according to its frequency and extending the list in that order.


Next Article

Similar Reads