Skip to content
Related Articles
Open in App
Not now

Related Articles

Python | Sort given list of strings by part of string

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 02 Jan, 2023
Improve Article
Save Article

Given a list of string, 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. Given below are a few methods to solve the given task.
Method #1: Using sort 

Python3




# Python code to demonstrate to sort list
# containing string by part of string
 
# Initialising list
ini_list = ["GeeksForGeeks abc", "manjeet xab", "akshat bac"]
 
# printing initial list
print ("initial list", str(ini_list))
 
# code to sort list
ini_list.sort(key = lambda x: x.split()[1])
     
# printing result
print ("result", str(ini_list))

Output:

initial list ['GeeksForGeeks abc', 'manjeet xab', 'akshat bac']
result ['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']

  Method #2: Using sorted 

Python3




# Python code to demonstrate to sort list
# containing string by part of string
 
# Initialising list
ini_list = ["GeeksForGeeks abc", "manjeet xab", "akshat bac"]
 
# printing initial list
print ("initial list", str(ini_list))
 
# code to sort list
res = sorted(ini_list, key = lambda x: x.split()[1])
     
# printing result
print ("result", res)

Output:

initial list ['GeeksForGeeks abc', 'manjeet xab', 'akshat bac']
result ['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']

Method #3: Using itemgetter

To split the string and sort the list by the second part of the string using the itemgetter function, you can do the following:

This will split each string into a list of two elements using the split function, and then pass the resulting list to the itemgetter function, which will retrieve the second element (the part of the string after the first space). The lambda function will then be used as the sorting key, so that the list is sorted based on the second element of each list.

Python3




from operator import itemgetter
 
# Initializing list
ini_list = ["GeeksForGeeks abc", "manjeet xab", "akshat bac"]
 
# Sorting the list
sorted_list = sorted(ini_list, key=lambda x: itemgetter(1)(x.split()))
 
# Printing the sorted list
print(sorted_list)
#This code is contributed by Edula Vinay Kumar Reddy

Output

['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']

Time complexity: O(n)

Auxiliary Space: O(n)


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!