Python | Sort given list of strings by part of string
Last Updated :
15 Jan, 2025
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
function
This method uses the list.sort()
function to sort the list in place and while sorting it applies it uses a lambda
function to extract the second word from each string as the sorting key.
Python
li = ["GeeksForGeeks abc", "manjeet xab", "akshat bac"]
# Sorting the list in place using a lambda function
li.sort(key=lambda s: s.split()[1])
print("Sorted list:", li)
OutputSorted list: ['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']
Explanation: sort()
function sorts the list li
in-place and the key
parameter is a lambda function that splits each string in the list by spaces and uses the second part (x.split()[1]
) as key for sorting.
Using sorted()
This method is very similar to the "Using sort
with Lambda " method given above but only difference between two methods is that sorted()
returns a new sorted list without modifying the original while sort()
sorts the list in-place and doesn't return anything.
Python
li = ["GeeksForGeeks abc", "manjeet xab", "akshat bac"]
# Sorting based on the second word
res = sorted(li, key=lambda x: x.split()[1])
print(res)
Output['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']
Using itemgetter() method
In this method we use itemgetter() method
to fetch the second part of each string after splitting, and sort the list based on that part.
Python
from operator import itemgetter
li = ["GeeksForGeeks abc", "manjeet xab", "akshat bac"]
# Sorting using itemgetter for the second part
res = sorted(li, key=lambda x: itemgetter(1)(x.split()))
print(res)
Output['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']
Explanation: itemgetter(1)
is used to retrieve the second part of each split string (after the space) and then lambda function defined by [ lambda x: itemgetter(1)(x.split()) ]
sorts the list based on this second part.
Using Regular Expressions
This approach uses the re.findall() function from the re module to extract the last word of each string and then sorts the list using the extracted words as the key.
Python
import re
li = ['GeeksForGeeks abc', 'manjeet xab', 'akshat bac']
regex = r'\w+$' # matches the last word of the string
# Sorting based on the last word using regular expression
res = sorted(li, key=lambda x: re.findall(regex, x)[0])
print(res)
Output['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']
Explanation:
re.findall(regex, x)
finds the last word in each string based on the regex pattern "\w+$"
lambda x: re.findall(regex, x)[0], is lambda function that
sorts the list using the extracted last word.
Using Counter Method with defaultdict
It uses defaultdict
to group strings by their second part without worrying about missing keys and then combines the sorted groups using list comprehension.
Python
from collections import defaultdict
li = ['GeeksForGeeks abc', 'manjeet xab', 'akshat bac']
# Grouping by second part
d = defaultdict(list)
for s in li:
substr = s.split()[1]
d[substr].append(s)
# Sorting and combining the result
res = [s for substr in sorted(d.keys()) for s in d[substr]]
print(res)
Output['GeeksForGeeks abc', 'akshat bac', 'manjeet xab']
Explanation:
d[substr].append(s)
groups strings by their second word and sorted(d.keys())
is used to sort these groups, then the final list is constructed using list comprehension to combine the sorted groups.
Similar Reads
Sort given list of strings by part the numeric part of string - Python We are given a list of strings containing both letters and numbers, and the goal is to sort them based on the numeric part within each string. To do this, we extract the digits, convert them to integers and use them as sorting keys. For example, in ["Gfg34", "is67", "be3st"], the numbers 34, 67, and
3 min read
Python program to split a string by the given list of strings Given a list of strings. The task is to split the string by the given list of strings. Input : test_str = 'geekforgeeksbestforgeeks', sub_list = ["best"] Output : ['geekforgeeks', 'best', 'forgeeks'] Explanation : "best" is extracted as different list element. Input : test_str = 'geekforgeeksbestfor
4 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 | Sort all sublists in given list of strings Sorting sublists in a list of strings refers to arranging the elements within each sublist in a specific order. There are multiple ways to sort each list in alphabetical order, let's understand each one by one.Using list comprehensionList comprehension with sorted() allows efficient sorting of each
2 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_datetim
2 min read