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

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']

How It Works

The sorting process follows these steps ?

  • The set(my_elem) removes duplicate characters from each string

  • Converting back to a list with list() allows us to use len()

  • Each string gets sorted by its unique character count in ascending order

Alternative Approach

You can simplify the function by removing the unnecessary list() conversion ?

def count_unique_chars(text):
    return len(set(text))

words = ['python', 'Will', 'Hi', 'how', 'fun', 'learn', 'code']
print("Original list:", words)

sorted_words = sorted(words, key=count_unique_chars)
print("Sorted by unique characters:", sorted_words)

# Show the unique character counts
for word in sorted_words:
    print(f"'{word}' has {count_unique_chars(word)} unique characters")
Original list: ['python', 'Will', 'Hi', 'how', 'fun', 'learn', 'code']
Sorted by unique characters: ['Hi', 'Will', 'how', 'fun', 'code', 'learn', 'python']
'Hi' has 2 unique characters
'Will' has 3 unique characters
'how' has 3 unique characters
'fun' has 3 unique characters
'code' has 4 unique characters
'learn' has 5 unique characters
'python' has 6 unique characters

Key Points

  • set() automatically removes duplicate characters from strings

  • len(set(string)) gives the count of unique characters

  • sort(key=function) modifies the original list

  • sorted(list, key=function) returns a new sorted list

Conclusion

Use len(set(string)) as a key function to sort strings by unique character count. The set() operation efficiently removes duplicates, making this approach both simple and effective.

Updated on: 2026-03-26T01:10:20+05:30

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements