Python program to Sort a List of Strings by the Number of Unique Characters

PythonServer Side ProgrammingProgramming

When it is required to sort a list of strings based on the number of unique characters, a method is defined that uses a ‘set’ operator, the ‘list’ method and the ‘len’ method.

Example

Below is a demonstration of the same −

def my_sort_func(my_elem):
   return len(list(set(my_elem)))

my_list = ['python', "Will", "Hi", "how", 'fun', 'learn', 'code']
print("The list is : ")
print(my_list)

my_list.sort(key = my_sort_func)

print("The result is :")
print(my_list)

Output

The list is :
['python', 'Will', 'Hi', 'how', 'fun', 'learn', 'code']
The result is :
['Hi', 'Will', 'how', 'fun', 'code', 'learn', 'python']

Explanation

  • A method named ‘my_sort_func’ is defined, that takes a string as a parameter.

  • It first extracts the unique elements from the list using ‘set’, and converts it to a set and then extracts the length of the list.

  • Outside the method, a list of strings is defined and is displayed on the console.

  • The list is sorted by specifying the key as the previously defined method.

  • The result is displayed on the console.

raja
Published on 08-Sep-2021 06:23:17
Advertisements