Python | Sort given list of strings by part of string

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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))

chevron_right


Output:

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

 
Method #2: Using sorted

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)

chevron_right


Output:

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


My Personal Notes arrow_drop_up

Programming freaktech Enthusiast and have interest in learning new upcoming technologies

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.