
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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']
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.
- Related Articles
- Program to find total number of strings, that contains one unique characters in Python
- Python How to sort a list of strings
- Convert list of strings and characters to list of characters in Python
- Python Program to Extract Strings with at least given number of characters from other list
- How to sort a list of strings in Python?
- Python – Sort given list of strings by numeric part of string
- Python – Sort given list of strings by part the numeric part of string
- Python program to Sort Strings by Punctuation count
- Python program to sort strings by substring range
- Python Program – Strings with all given List characters
- Python – Sort by Rear Character in Strings List
- Python program to sort a list of tuples by second Item
- Python Program to Sort A List Of Names By Last Name
- Python program to Sort a List of Dictionaries by the Sum of their Values
- Program to find the number of unique integers in a sorted list in Python

Advertisements