Python | Sort given list by frequency and remove duplicates

Problems associated with sorting and removal of duplicates is quite common in development domain and general coding as well. The sorting by frequency has been discussed, but sometimes, we even wish to remove the duplicates without using more LOC’s and in a shorter way. Let’s discuss certain ways in which this can be done.

Method #1 : Using count() + set() + sorted()

The sorted function can be used to sort the elements as desired, the frequency can be computed using the count function and removal of duplicates can be handled using the set function.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# sorting and removal of duplicates
# Using sorted() + set() + count()
  
# initializing list
test_list = [5, 6, 2, 5, 3, 3, 6, 5, 5, 6, 5]
  
# printing original list
print("The original list : " + str(test_list))
  
# using sorted() + set() + count()
# sorting and removal of duplicates
res = sorted(set(test_list), key = lambda ele: test_list.count(ele))
  
# print result
print("The list after sorting and removal : " + str(res))

chevron_right


Output :

The original list : [5, 6, 2, 5, 3, 3, 6, 5, 5, 6, 5]
The list after sorting and removal : [2, 3, 6, 5]

 

Method #2 : Using Counter.most_common() + list comprehension

If one has a particular use case of sorting by the decreasing order of frequency, one can also use most-common function of Counter library to get frequency part.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate
# sorting and removal of duplicates
# Using Counter.most_common() + list comprehension
from collections import Counter
  
# initializing list
test_list = [5, 6, 2, 5, 3, 3, 6, 5, 5, 6, 5]
  
# printing original list
print("The original list : " + str(test_list))
  
# using Counter.most_common() + list comprehension
# sorting and removal of duplicates
res = [key for key, value in Counter(test_list).most_common()]
  
# print result
print("The list after sorting and removal : " + str(res))

chevron_right


Output :

The original list : [5, 6, 2, 5, 3, 3, 6, 5, 5, 6, 5]
The list after sorting and removal : [5, 6, 3, 2]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.