Sort List Elements by Frequency – Python
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().
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)
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.
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)
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.
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)
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.