Open In App

Python | Sort each String in String list

Last Updated : 09 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
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.



Similar Reads

Python program to Sort a List of Tuples in Increasing Order by the Last Element in Each Tuple
The task is to write a Python Program to sort a list of tuples in increasing order by the last element in each tuple. Input: [(1, 3), (3, 2), (2, 1)] Output: [(2, 1), (3, 2), (1, 3)] Explanation: sort tuple based on the last digit of each tuple. Methods #1: Using sorted(). Sorted() method sorts a list and always returns a list with the elements in
7 min read
Sort a list in Python without sort Function
Python Lists are a type of data structure that is mutable in nature. This means that we can modify the elements in the list. We can sort a list in Python using the inbuilt list sort() function. But in this article, we will learn how we can sort a list in a particular order without using the list sort() method. Sort a List Without Using Sort Functio
3 min read
Python IMDbPY – Get each episode name of each season of the series
In this article we will see how we can get the name/title of each episode for each season of the series from the episodes info set. Each series have seasons and each season has multiple episodes i.e episode is the subset of season and season is the subset of series. We get the episodes by adding episodes info set to the series In order to get this
3 min read
Python IMDbPY – Getting each episode year of each season of the series
In this article we will see how we can get the year of each episode for each season of the series from the episodes info set. Each series have seasons and each season has multiple episodes i.e episode is the subset of season and season is the subset of series. We get the episodes details by adding episodes info set to the series In order to get thi
3 min read
Python IMDbPY – Get each episode ID of each season of the series
In this article we will see how we can get the id of each episode for each season of the series from the episodes info set. Each series have seasons and each season has multiple episodes i.e episode is the subset of season and season is the subset of series. We get the episodes details by adding episodes info set to the series In order to get this
2 min read
Python - Remove front K characters from each string in String List
Sometimes, we come across an issue in which we require to delete the first K characters from each string, that we might have added by mistake and we need to extend this to the whole list. This type of utility is common in web development. Having shorthands to perform this particular job is always a plus. Let’s discuss certain ways in which this can
6 min read
Python program to create a list of tuples from given list having number and its cube in each tuple
Given a list of numbers of list, write a Python program to create a list of tuples having first element as the number and second element as the cube of the number. Example: Input: list = [1, 2, 3] Output: [(1, 1), (2, 8), (3, 27)] Input: list = [9, 5, 6] Output: [(9, 729), (5, 125), (6, 216)] Method #1 : Using pow() function.We can use list compreh
5 min read
Python program to get the indices of each element of one list in another list
Given 2 lists, get all the indices of all occurrence of each element in list2 from list1. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 4] Output : [[3], [1, 9], [0, 7]] Explanation : 5 is present at 1st and 9th index. Input : test_list = [4, 5, 3, 7, 8, 3, 2, 4, 3, 5, 8, 3], get_list = [7, 5, 8] Output : [[3], [1, 9],
7 min read
Python Program to Square Each Odd Number in a List using List Comprehension
Given a list, the task is to write a Python Program to square each odd number in a list using list comprehension. Square Each Odd Number in a List using List Comprehension List comprehensions are used for creating new lists from other iterables like tuples, strings, arrays, lists, etc. A list comprehension consists of brackets containing the expres
3 min read
Sorting List of Lists with First Element of Each Sub-List in Python
In Python, sorting a list of lists by the first element of each sub-list is a common task. Whether you're dealing with data points, coordinates, or any other structured information, arranging the lists based on the values of their first elements can be crucial. In this article, we will sort a list of lists by the first element of each sub-list. Thi
3 min read
three90RightbarBannerImg