Python | Sort this list by frequency and remove duplicates

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

The sort function can be used to sort items as desired, the frequency can be calculated using counting functions, and the removal of duplicates can be handled with the install function.

# Python3 demo code
# sorting and removing duplicates
# Using sorted () + set () + count ()

 
# initializing list

test_list = [ 5 , 6 , 2 , 5 , 3 , 3 , 6 , 5 , 5 , 6 , 5 ]

 
# print original list

print ( "The original list:" + str (test_list))

 
# using sorted () + set () + count ()
# sorting and removing duplicates

res = sorted ( set (test_list), key = lambda ele: test_list.count (ele))

 
# print result

print ( "The list after sorting and removal:" + str (res))

Exit:

 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 there is a specific use case with By frequency descending ordering, you can also use the most common Counter library function to get the frequency part.

# Python3 demo code
# sort and remove 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 ]

 
# print the original list

print ( "The original list:" + str (test_list))

 
# using Counter.most_common () + comprehension list
# sort and remove duplicate ov

res = [key for key, value in Counter (test_list) .most_common ()]

 
# print result

print ( "The list after sorting and removal: " + str (res))

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]