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.
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.
The original list : [5, 6, 2, 5, 3, 3, 6, 5, 5, 6, 5] The list after sorting and removal : [5, 6, 3, 2]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course