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]
- 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 all duplicates and permutations in nested list
- Python | Remove duplicates based on Kth element tuple list
- Python | Sort list elements by frequency
- List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)
- Remove all duplicates from a given string in Python
- Python | Remove duplicates in Matrix
- Python | Remove all duplicates words from a given sentence
- Python groupby method to remove all consecutive duplicates
- Python | Merging duplicates to list of list
- Python | List frequency of elements
- Python | Consecutive duplicates all elements deletion in 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 email@example.com. 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.