- Trending Categories
- Data Structure
- Operating System
- MS Excel
- C Programming
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python â€“ Sort by Uppercase Frequency
When it is required to sort the elements of the list by frequency of uppercase elements, a method is defined that uses list comprehension and the ‘isupper’ method.
Below is a demonstration of the same −
def higher_character_sort(sub): return len([ele for ele in sub if ele.isupper()]) my_list = ["pyt", "is", "FUN", "to", "Learn"] print("The list is:") print(my_list) my_list.sort(key=higher_character_sort) print("The result is:") print(my_list)
The list is: ['pyt', 'is', 'FUN', 'to', 'Learn'] The result is: ['pyt', 'is', 'to', 'Learn', 'FUN']
A method named ‘higher_character_sort’ is defined that tales an element as parameter.
A list comprehension is used to iterate over the elements and the ‘isupper’ method is used to check if the element is upper case letter or lower case letter.
The length of this output is returned as output.
Outside the method, a list of strings is defined and displayed on the console.
The list is sorted using the ‘sort’ method and the key is specified as the previously defined method.
This is displayed as output on the console.
Kickstart Your Career
Get certified by completing the courseGet Started