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:
Reverse All Strings in String List in Python
Next article icon

Python | Sort each String in String list

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

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 : Using list comprehension + sorted() + join() This is one way in which this problem can be solved. In this, we use sorted() functionality to perform sort operation and join() is used to reconstruct the string list. 

Python3




# Python3 code to demonstrate working of
# Sort Strings in String list
# using list comprehension + sorted() + join()
 
# initialize list
test_list = ['gfg', 'is', 'good']
 
# printing original list
print("The original list : " + str(test_list))
 
# Sort Strings in String list
# using list comprehension + sorted() + join()
res = [''.join(sorted(ele)) for ele in test_list]
 
# printing result
print("List after string sorting : " + str(res))
 
 
Output : 
The original list : ['gfg', 'is', 'good'] List after string sorting : ['fgg', 'is', 'dgoo']

Time Complexity: O(n*nlogn) where n is the number of elements in the string list. The list comprehension + sorted() + join() is used to perform the task and it takes O(n*nlogn) time.
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the string list.

  Method #2 : Using map() + sorted() + join() + lambda The combination of above method can also be used to perform this task. In this, we perform the functionality of traversal using map() and lambda rather than list comprehension.

Python3




# Python3 code to demonstrate working of
# Sort Strings in String list
# using map() + sorted() + join() + lambda
 
# initialize list
test_list = ['gfg', 'is', 'good']
 
# printing original list
print("The original list : " + str(test_list))
 
# Sort Strings in String list
# using map() + sorted() + join() + lambda
res = list(map(lambda ele: "".join(sorted(ele)), test_list))
 
# printing result
print("List after string sorting : " + str(res))
 
 
Output : 
The original list : ['gfg', 'is', 'good'] List after string sorting : ['fgg', 'is', 'dgoo']

Time Complexity: O(n*nlogn), where n is the length of the input list. This is because we’re using map() + sorted() + join() + lambda which has a time complexity of O(n*nlogn) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.

Method #3: Using reduce()

Algorithm

  1. Initialize an empty list res
  2. For each string s in test_list, do the following:
    a. Sort the characters in s using sorted()
    b. Join the sorted characters back together into a string using join()
    c. Append the sorted string to res
  3. Return res.

Python3




# Python3 code to demonstrate working of
# Sort Strings in String list
# using reduce() + sorted() + join()
 
from functools import reduce
 
# initialize list
test_list = ['gfg', 'is', 'good']
 
# printing original list
print("The original list : " + str(test_list))
 
# Sort Strings in String list
# using reduce() + sorted() + join()
res = reduce(lambda x, y: x + [''.join(sorted(y))], test_list, [])
 
# printing result
print("List after string sorting : " + str(res))
#This code is contributed by Vinay Pinjala.
 
 
Output
The original list : ['gfg', 'is', 'good'] List after string sorting : ['fgg', 'is', 'dgoo']

Time complexity: O(n * m * log(m)), where n is the length of the list test_list and m is the maximum length of a string in test_list. This is because sorted() takes O(m * log(m)) time to sort each string in test_list, and reduce() takes O(n) time to iterate over each element in test_list.

Space complexity: O(n * m), where n is the length of the list test_list and m is the maximum length of a string in test_list. This is because the reduce() function creates a new list res with one element for each element in test_list, and each element in res takes up to m characters.



Next Article
Reverse All Strings in String List in Python
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python list-programs
  • Python-sort
Practice Tags :
  • python

Similar Reads

  • How to sort a list of strings in Python
    In this article, we will explore various methods to sort a list of strings in Python. The simplest approach is by using sort(). Using sort() MethodThe sort() method sorts a list in place and modifying the original list directly. [GFGTABS] Python a = ["banana", "apple", "cher
    2 min read
  • Python | Alternate Sort in String list
    Sometimes, while working with Python list, we can have a problem in which we need to perform sorting only of alternatively in list. This kind of application can come many times. Let's discuss certain way in which this task can be performed. Method : Using join() + enumerate() + generator expression
    2 min read
  • Reverse All Strings in String List in Python
    We are given a list of strings and our task is to reverse each string in the list while keeping the order of the list itself unchanged. For example, if we have a list like this: ['gfg', 'is', 'best'] then the output will be ['gfg', 'si', 'tseb']. Using For LoopWe can use a for loop to iterate over t
    2 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
  • Python | Sort given list of strings by part of string
    We are given with a list of strings, the task is to sort the list by part of the string which is separated by some character. In this scenario, we are considering the string to be separated by space, which means it has to be sorted by second part of each string. Using sort() with lambda functionThis
    3 min read
  • Python | Splitting string list by strings
    Sometimes, while working with Python strings, we might have a problem in which we need to perform a split on a string. But we can have a more complex problem of having a front and rear string and need to perform a split on them. This can be multiple pairs for split. Let's discuss certain way to solv
    3 min read
  • Python - Sort String by Custom Integer Substrings
    Given a list of strings, sort strings by the occurrence of substring from list. Input : test_list = ["Good at 4", "Wake at 7", "Work till 6", "Sleep at 11"], subord_list = ["11", "7", "4", "6"] Output : ['Sleep at 11', 'Wake at 7', 'Good at 4', 'Work till 6'] Explanation : Strings sorted by substrin
    5 min read
  • Python - Sort by Rear Character in Strings List
    Given a String list, perform sort by the rear character in the Strings list. Input : test_list = ['gfg', 'is', 'for', 'geeks'] Output : ['gfg', 'for', 'is', 'geeks'] Explanation : g < r < s = s, hence the order. Input : test_list = ['gfz', 'is', 'for', 'geeks'] Output : ['for', 'is', 'geeks',
    6 min read
  • Python - Extract Sorted Strings
    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
    5 min read
  • Python | Sort list of dates given as strings
    To sort a list of dates given as strings in Python, we can convert the date strings to datetime objects for accurate comparison. Once converted, the list can be sorted using Python's built-in sorted() or list.sort() functions. This ensures the dates are sorted chronologically. Using pandas.to_dateti
    3 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