Sort List Elements by Frequency - Python
Last Updated :
12 Feb, 2025
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().
Python
from collections import Counter
a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"]
# Count frequency of each element in a
freq = Counter(a)
# Sort list a based on frequency (highest frequency first)
res = sorted(a, key=lambda x: -freq[x])
print(res)
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.
Python
from collections import Counter
a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"]
freq = Counter(a)
res = []
for item, count in freq.most_common():
res.extend([item] * count)
print(res)
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.
Python
a = ["Aryan", "Harsh", "Aryan", "Kunal", "Harsh", "Aryan"]
# Manually count frequency of each element
freq = {}
for x in a:
freq[x] = freq.get(x, 0) + 1
# Sort the keys based on their frequency in descending order
sorted_keys = sorted(freq.keys(), key=lambda x: freq[x], reverse=True)
# Rebuild the list by extending each key repeated by its frequency
res = []
for key in sorted_keys:
res.extend([key] * freq[key])
print(res)
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.
Similar Reads
Python - List Frequency of Elements We are given a list we need to count frequencies of all elements in given list. For example, n = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4] we need to count frequencies so that output should be {4: 4, 3: 3, 2: 2, 1: 1}.Using collections.Countercollections.Counter class provides a dictionary-like structure that
2 min read
Python - Step Frequency of elements in List Sometimes, while working with Python, we can have a problem in which we need to compute frequency in list. This is quite common problem and can have usecase in many domains. But we can atimes have problem in which we need incremental count of elements in list. Let's discuss certain ways in which thi
4 min read
Python - Elements frequency in Tuple Given a Tuple, find the frequency of each element. Input : test_tup = (4, 5, 4, 5, 6, 6, 5) Output : {4: 2, 5: 3, 6: 2} Explanation : Frequency of 4 is 2 and so on.. Input : test_tup = (4, 5, 4, 5, 6, 6, 6) Output : {4: 2, 5: 2, 6: 3} Explanation : Frequency of 4 is 2 and so on.. Method #1 Using def
7 min read
Python - Sort by Frequency of second element in Tuple List Given list of tuples, sort by frequency of second element of tuple. Input : test_list = [(6, 5), (1, 7), (2, 5), (8, 7), (9, 8), (3, 7)] Output : [(1, 7), (8, 7), (3, 7), (6, 5), (2, 5), (9, 8)] Explanation : 7 occurs 3 times as 2nd element, hence all tuples with 7, are aligned first. Input : test_l
6 min read
Python | Group list elements based on frequency Given a list of elements, write a Python program to group list elements and their respective frequency within a tuple. Examples: Input : [1, 3, 4, 4, 1, 5, 3, 1] Output : [(1, 3), (3, 2), (4, 2), (5, 1)] Input : ['x', 'a', 'x', 'y', 'a', 'x'] Output : [('x', 3), ('a', 2), ('y', 1)] Method #1: List c
5 min read