
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort List of Strings by Number of Unique Characters in Python
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.
Advertisements