Python - Sort by Rear Character in Strings List
Last Updated :
06 Apr, 2023
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', 'gfz']
Explanation : r < s = s < z, hence the order.
Method #1 : Using sort()
In this, we perform the task of sorting using sort(), and an external function is used for the task of getting the rear element in string.
Python3
# Python3 code to demonstrate working of
# Sort by Rear Character in Strings List
# Using sort()
# sort key function
def get_rear(sub):
return sub[-1]
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list is : " + str(test_list))
# using sort with key fnc.
# performs inplace sort
test_list.sort(key = get_rear)
# printing result
print("Sorted List : " + str(test_list))
OutputThe original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Sorted List : ['gfg', 'for', 'is', 'geeks', 'best']
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
Method #2 : Using sorted() + lambda
In this, we use sorted() for performing sort, explicit, and use a lambda function to perform the task of getting the rear element.
Python3
# Python3 code to demonstrate working of
# Sort by Rear Character in Strings List
# Using sorted() + lambda
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list is : " + str(test_list))
# lambda function for rear element
# performs non-inplace sort
res = sorted(test_list, key = lambda sub : sub[-1])
# printing result
print("Sorted List : " + str(res))
OutputThe original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Sorted List : ['gfg', 'for', 'is', 'geeks', 'best']
Time Complexity: O(nlogn)
Auxiliary Space: O(n)
Method#3: Using Recursive method.
Python3
# Python3 code to demonstrate working of
# Sort by Rear Character in Strings List
# Using recursive method
def sort_by_last_char(lst):
if len(lst) <= 1:
return lst
pivot = lst[0]
less = [x for x in lst[1:] if x[-1] < pivot[-1]]
greater = [x for x in lst[1:] if x[-1] >= pivot[-1]]
return sort_by_last_char(less) + [pivot] + sort_by_last_char(greater)
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list is : " + str(test_list))
result = sort_by_last_char(test_list)
# printing result
print("Sorted List:", result)
#this code contributed by tvsk
OutputThe original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Sorted List: ['gfg', 'for', 'is', 'geeks', 'best']
Time Complexity: O(n log n)
Auxiliary Space: O(n)
Method #4: Using map(), list(), and lambda
- Convert the list of strings into a list of tuples where each tuple has two elements - the original string and the last character of that string.
- Use the map() function to apply the lambda function lambda x: x[1] on each tuple, which returns the last character of each string.
- Use the sorted() function on the list of tuples to sort the list based on the last character of each string.
- Use the map() function again to extract only the original strings from the sorted list of tuples.
- Use the list() function to convert the map object into a list.
Python3
def sort_by_last_char(lst):
sorted_tuples = sorted([(s, s[-1]) for s in lst], key=lambda x: x[1])
sorted_strings = list(map(lambda x: x[0], sorted_tuples))
return sorted_strings
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list is : " + str(test_list))
result = sort_by_last_char(test_list)
# printing result
print("Sorted List:", result)
OutputThe original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Sorted List: ['gfg', 'for', 'is', 'geeks', 'best']
Time Complexity: O(nlogn) - Sorting the list of tuples takes O(nlogn) time.
Auxiliary Space: O(n) - Creating a new list of tuples with size n.
Method #5: Using a Dictionary and List Comprehension
- Create a dictionary with the last character of each string as key and the string as value.
- Sort the dictionary based on the keys.
- Create a list comprehension to append the sorted strings to a new list.
Python3
def sort_by_last_char(lst):
my_dict = {}
for s in lst:
if s[-1] not in my_dict:
my_dict[s[-1]] = [s]
else:
my_dict[s[-1]].append(s)
sorted_dict = dict(sorted(my_dict.items()))
sorted_strings = [j for i in sorted_dict.values() for j in sorted(i)]
return sorted_strings
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list is : " + str(test_list))
result = sort_by_last_char(test_list)
# printing result
print("Sorted List:", result)
OutputThe original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Sorted List: ['gfg', 'for', 'geeks', 'is', 'best']
Time Complexity: O(n log n) due to the use of sorting function.
Auxiliary Space: O(n) for the dictionary and list.
Method #6: Using a custom comparator function
- Define a custom function compare_strings() that takes a string s and returns the last character of the string.
- Initialize a list test_list with some string elements.
- Print the original list using the print() function and concatenation with a string message.
- Use the sorted() function with the key parameter to sort the test_list based on the last character of each string. The key parameter takes a function that is applied to each element of the list to get a sorting key, and the sorted() function returns a new sorted list.
- Assign the sorted list to the variable sorted_list.
- Print the sorted list using the print() function and concatenation with a string message.
Python3
# custom comparator function
def compare_strings(s):
return s[-1]
# initializing list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list is : " + str(test_list))
# using sorted with custom key function
# returns a new sorted list
sorted_list = sorted(test_list, key=compare_strings)
# printing result
print("Sorted List : " + str(sorted_list))
OutputThe original list is : ['gfg', 'is', 'best', 'for', 'geeks']
Sorted List : ['gfg', 'for', 'is', 'geeks', 'best']
Time Complexity: O(n log n) - The sorting algorithm has a time complexity of O(n log n).
Auxiliary Space: O(n) - The sorting algorithm requires O(n) space to store the sorted list.
Similar Reads
Python - Sort String list by K character frequency Given String list, perform sort operation on basis of frequency of particular character. Input : test_list = ["geekforgeekss", "is", "bessst", "for", "geeks"], K = 's' Output : ['bessst', 'geekforgeekss', 'geeks', 'is', 'for'] Explanation : bessst has 3 occurrence, geeksforgeekss has 3, and so on. I
4 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
Python - Remove Rear K characters from String List Sometimes, we come across an issue in which we require to delete the last 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 plu
5 min read
Python - Sort Strings by maximum frequency character Given a string, the task is to write a Python program to perform sort by maximum occurring character. Input : test_list = ["geekforgeeks", "bettered", "for", "geeks"] Output : ['for', 'geeks', 'bettered', 'geekforgeeks'] Explanation : 1 < 2 < 3 < 4, is ordering of maximum character occurren
3 min read
Python | Strings with similar front and rear character Sometimes, while programming, we can have a problem in which we need to check for the front and rear characters of each string. We may require to extract the count of all strings with similar front and rear characters. Let's discuss certain ways in which this task can be performed. Method #1: Using
4 min read
Python - Group list by first character of string Sometimes, we have a use case in which we need to perform the grouping of strings by various factors, like first letter or any other factor. These types of problems are typical to database queries and hence can occur in web development while programming. This article focuses on one such grouping by
7 min read