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.
- Python | Remove all duplicates and permutations in nested list
- Python Remove Duplicates from a List
- Python - Ways to remove duplicates from list
- Python | Remove consecutive duplicates from list
- Python | Remove duplicates from nested list
- Python | Remove duplicates based on Kth element tuple list
- Python | Remove all duplicates words from a given sentence
- Remove all duplicates from a given string in Python
- Python - Remove Equilength and Equisum Tuple Duplicates
- Python | Merging duplicates to list of list
- Python | Sort list elements by frequency
- Python - Sort String list by K character frequency
- Python - Sort by Frequency of second element in Tuple List
- Python groupby method to remove all consecutive duplicates
- Python | Remove duplicates in Matrix
- Python - Remove Kth Index Duplicates in Tuple
- Python - Remove alternate consecutive duplicates
- Python - Remove K length Duplicates from String
- Maximum length prefix such that frequency of each character is atmost number of characters with minimum frequency
- Generate a list using given frequency list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.