
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
Extract Sorted Strings in Python
When it is required to extract sorted strings, a list comprehension and the ‘sorted’ method is used.
Example
Below is a demonstration of the same −
my_list = ["pyt", "Fdf", "Fun"] print("The list is :") print(my_list) my_result = [element for element in my_list if ''.join(sorted(element)) == element] print("The result is :") print(my_result)
Output
The list is : ['pyt', 'Fdf', 'Fun'] The result is : ['Fdf']
Explanation
A list is defined and displayed on the console.
A list comprehension is used to iterate over the list, and every element is sorted ad checked to see if it is equal to the current element, and then the 'join' method is used.
This result is assigned to a variable.
This is the output that is displayed on the console.
Advertisements