Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 stringConverting back to a list with
list()allows us to uselen()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 stringslen(set(string))gives the count of unique characterssort(key=function)modifies the original listsorted(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.
