Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Extract K length substrings
Next article icon

Python – Extract Sorted Strings

Last Updated : 25 Apr, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a String List, extract all sorted strings.

Input : test_list = ["hint", "geeks", "fins", "Gfg"]  Output : ['hint', 'fins', 'Gfg']  Explanation : Strings in increasing order of characters are extracted.
Input : test_list = ["hint", "geeks", "Gfg"]  Output : ['hint', 'Gfg']  Explanation : Strings in increasing order of characters are extracted. 

Method #1 : Using list comprehension + sorted()

In this, we perform the task of sorting strings and comparison using sorted(), list comprehension is used to iterate through Strings.

Python3




# Python3 code to demonstrate working of
# Extract sorted strings
# Using list comprehension + sorted()
 
# initializing list
test_list = ["hint", "geeks", "fins", "Gfg"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# sorted(), converts to sorted version and compares with
# original string
res = [sub for sub in test_list if ''.join(sorted(sub)) == sub]
 
# printing result
print("Sorted Strings : " + str(res))
 
 
Output
The original list is : ['hint', 'geeks', 'fins', 'Gfg'] Sorted Strings : ['hint', 'fins', 'Gfg']

Time complexity: O(nlogn + n * klogk), where n is the number of strings in the list and k is the maximum length of a string in the list.
Auxiliary space: O(n), as we are creating a new list with the sorted strings.

Method #2 : Using filter() + lambda + sorted() + join()

In this, we perform filtering using filter() + lambda, and join() is used to convert the final sorted character list result to a string for comparison.

Python3




# Python3 code to demonstrate working of
# Extract sorted strings
# Using filter() + lambda + sorted() + join()
 
# initializing list
test_list = ["hint", "geeks", "fins", "Gfg"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# sorted(), converts to sorted version and compares with
# original string
res = list(filter(lambda sub: ''.join(sorted(sub)) == sub, test_list))
 
# printing result
print("Sorted Strings : " + str(res))
 
 
Output
The original list is : ['hint', 'geeks', 'fins', 'Gfg'] Sorted Strings : ['hint', 'fins', 'Gfg']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #3 : Using extend()+sort() methods

Python3




# Python3 code to demonstrate working of
# Extract sorted strings
 
# initializing list
test_list = ["hint", "geeks", "fins", "Gfg"]
 
# printing original list
print("The original list is : " + str(test_list))
 
res = []
 
for i in test_list:
    x = list(i)
    y = []
    y.extend(x)
    y.sort()
    if(x == y):
        res.append(i)
 
# printing result
print("Sorted Strings : " + str(res))
 
 
Output
The original list is : ['hint', 'geeks', 'fins', 'Gfg'] Sorted Strings : ['hint', 'fins', 'Gfg']

Time Complexity: O(n)
Auxiliary Space: O(n)

Method #4: Using a for loop and a separate list for storing sorted strings

  1. Initialize an empty list to store the sorted strings.
  2. Loop through each string in the input list.
  3. For each string, use the sorted() function to sort the characters in the string in ascending order and then join them back into a string.
  4. Compare the sorted string obtained in step 3 with the original string.
  5. If the sorted string is equal to the original string, it means that the original string contains characters in sorted order, so append it to the list of sorted strings.
  6. After processing all strings in the input list, return the list of sorted strings.

Python3




# Python3 code to demonstrate working of
# Extract sorted strings
# Using for loop and a separate list for storing sorted strings
 
# initializing list
test_list = ["hint", "geeks", "fins", "Gfg"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using for loop to check each string
res = []
for string in test_list:
    if ''.join(sorted(string)) == string:
        res.append(string)
 
# printing result
print("Sorted Strings : " + str(res))
 
 
Output
The original list is : ['hint', 'geeks', 'fins', 'Gfg'] Sorted Strings : ['hint', 'fins', 'Gfg']

Time complexity: O(n * klogk), where n is the length of the input list and k is the maximum length of a string in the list, due to the sorting operation.
Auxiliary space: O(n), for storing the output list of sorted strings.

Method #5: Using a generator expression with sorted() and if condition

In this method, we can use a generator expression with sorted() function and an if condition to check if the sorted string is equal to the original string. If it is, we can yield the original string.

 Approach:

  1. Use a generator expression with sorted() function to check if the sorted string is equal to the original string.
  2. Yield the original string if it is sorted.

Python3




# Python3 code to demonstrate working of
# Extract sorted strings
# Using generator expression with sorted() and if condition
 
# initializing list
test_list = ["hint", "geeks", "fins", "Gfg"]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using generator expression to check each string
res = (string for string in test_list if ''.join(sorted(string)) == string)
 
# printing result
print("Sorted Strings : " + str(list(res)))
 
 
Output
The original list is : ['hint', 'geeks', 'fins', 'Gfg'] Sorted Strings : ['hint', 'fins', 'Gfg']

Time complexity: O(n * k log k), where n is the length of the list and k is the length of the longest string in the list.
Auxiliary space: O(n), where n is the length of the list.



Next Article
Python - Extract K length substrings
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • Python | Extract K sized strings
    Sometimes, while working with huge amount of data, we can have a problem in which we need to extract just specific sized strings. This kind of problem can occur during validation cases across many domains. Let's discuss certain ways to handle this in Python strings list. Method #1 : Using list compr
    5 min read
  • Python - Extract range sized strings
    Sometimes, while working with huge amount of data, we can have a problem in which we need to extract just specific range sized strings. This kind of problem can occur during validation cases across many domains. Let’s discuss certain ways to handle this in Python strings list. Method #1 : Using list
    4 min read
  • Python | Extract Score list of String
    Sometimes, while programming we can have a problem in which we dedicate to each character of alphabets a particular score and then according to string, extract only those score for further computations. This can have application in gaming domain. Let's discuss certain ways in which this task can be
    3 min read
  • Python Extract Substring Using Regex
    Python provides a powerful and flexible module called re for working with regular expressions. Regular expressions (regex) are a sequence of characters that define a search pattern, and they can be incredibly useful for extracting substrings from strings. In this article, we'll explore four simple a
    2 min read
  • Python - Extract K length substrings
    The task is to extract all possible substrings of a specific length, k. This problem involves identifying and retrieving those substrings in an efficient way. Let's explore various methods to extract substrings of length k from a given string in Python Using List Comprehension List comprehension is
    3 min read
  • Python | Sort each String in String list
    Sometimes, while working with Python, we can have a problem in which we need to perform the sort operation in all the Strings that are present in a list. This problem can occur in general programming and web development. Let's discuss certain ways in which this problem can be solved. Method #1 : Usi
    4 min read
  • Python Program to Sort a String
    Sorting strings in Python is a common and important task, whether we need to organize letters alphabetically or systematically handle text data. In this article, we will explore different methods to sort a string starting from the most efficient to the least. Using sorted with join()sorted() functio
    2 min read
  • Reverse Sort a String - Python
    The goal is to take a given string and arrange its characters in descending order based on their Unicode values. For example, in the string "geeksforgeeks", the characters will be sorted from highest to lowest, resulting in a new string like "ssrokkggfeeeee". Let's understand different methods to pe
    2 min read
  • Python | K Character Split String
    The problems and at the same time applications of list splitting is quite common while working with python strings. Some characters are usually tend to ignore in the use cases. But sometimes, we might not need to omit those characters but include them in our programming output. Let’s discuss certain
    4 min read
  • Sort Numeric Strings in a List - Python
    We are given a list of numeric strings and our task is to sort the list based on their numeric values rather than their lexicographical order. For example, if we have: a = ["10", "2", "30", "4"] then the expected output should be: ["2", "4", "10", "30"] because numerically, 2 < 4 < 10 < 30.
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences