Open In App

Python – Sort by Rear Character in Strings List

Last Updated : 06 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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


Output

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


Output

The 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


Output

The 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

  1. 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.
  2. Use the map() function to apply the lambda function lambda x: x[1] on each tuple, which returns the last character of each string.
  3. Use the sorted() function on the list of tuples to sort the list based on the last character of each string.
  4. Use the map() function again to extract only the original strings from the sorted list of tuples.
  5. 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)


Output

The 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

  1. Create a dictionary with the last character of each string as key and the string as value.
  2. Sort the dictionary based on the keys.
  3. 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)


Output

The 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

  1. Define a custom function compare_strings() that takes a string s and returns the last character of the string.
  2. Initialize a list test_list with some string elements.
  3. Print the original list using the print() function and concatenation with a string message.
  4. 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.
  5. Assign the sorted list to the variable sorted_list.
  6. 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))


Output

The 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.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads