GeeksforGeeks App
Open App
Browser
Continue

# Python – Sort on basis of reverse Strings

Given a String list, sort list on basis of reverse of strings.

Input : test_list = [“gfg”, “is”, “best”, “geeks”] Output : [‘gfg’, ‘is’, ‘geeks’, ‘best’] Explanation : g < is < ks < t [elements from rear], hence the order. Input : test_list = [“gfg”, “is”, “best”] Output : [‘gfg’, ‘is’, ‘best’] Explanation : g < s < t [elements from rear], hence the order.

Method #1 : Using sort() + reverse()

This is one of the ways in which this task can be performed. In this, we first reverse each element, perform sort and then again reverse each  string to get resultant ordering.

## Python3

 `# Python3 code to demonstrate working of``# Sort on basis of reverse Strings``# Using reverse() + sort()` `# initializing list``test_list ``=` `[``"gfg"``, ``"is"``, ``"best"``, ``"for"``, ``"geeks"``]` `# printing original list``print``(``"The original list : "` `+` `str``(test_list))` `# reverse() to reverse each string``res ``=` `[]``for` `ele ``in` `test_list:``    ``res.append("".join(``reversed``(ele)))``    ` `# sorting to get required ordering``res.sort()` `# reverse each element again``test_list ``=` `[]``for` `ele ``in` `res:``    ``test_list.append("".join(``reversed``(ele)))``    ` `# printing result``print``(``"List after sorting on reversed strings : "` `+` `str``(test_list))`

Output

```The original list : ['gfg', 'is', 'best', 'for', 'geeks']
List after sorting on reversed strings : ['gfg', 'for', 'is', 'geeks', 'best']```

Time Complexity: O(nlogn), where n is the elements of list
Auxiliary Space: O(n), where n is the size of list

Method #2 : Using list slicing  + sort()

This is yet another way in which this task can be performed. in this list slicing is used to perform reverse operation and sort() is used to sort, in one liner.

## Python3

 `# Python3 code to demonstrate working of``# Sort on basis of reverse Strings``# Using list slicing + sort()` `# initializing list``test_list ``=` `[``"gfg"``, ``"is"``, ``"best"``, ``"for"``, ``"geeks"``]` `# printing original list``print``(``"The original list : "` `+` `str``(test_list))` `# [::-1] to reverse each string``# sort() to sort``test_list.sort(key ``=` `lambda` `sub: sub[::``-``1``])` `# printing result``print``(``"List after sorting on reversed strings : "` `+` `str``(test_list))`

Output

```The original list : ['gfg', 'is', 'best', 'for', 'geeks']
List after sorting on reversed strings : ['gfg', 'for', 'is', 'geeks', 'best']```

Time Complexity: O(nlogn) where n is the number of elements in the list “test_list”.
Auxiliary Space: O(n) where n is the number of elements in the list “test_list”.

Method 3 : Using a for loop to iterate through the list and swap adjacent elements based on their reverse string value.

step by step approach.

1. Import the itertools module.
2. Initialize a list of strings named test_list.
3. Print the original list.
4. Use a for loop to iterate through each element in the list.
5. Inside the for loop, use another for loop to iterate through the remaining elements in the list.
6. Compare the reversed form of the current element with the reversed form of the next element using an if statement.
7. If the current element is greater than the next element in terms of their reversed form, swap their positions in the list using tuple assignment.
8. Print the sorted list based on their reversed form.

## Python3

 `# Python3 code to demonstrate working of``# Sort on basis of reverse Strings``# Using for loop and swapping adjacent elements` `# initializing list``test_list ``=` `[``"gfg"``, ``"is"``, ``"best"``, ``"for"``, ``"geeks"``]` `# printing original list``print``(``"The original list : "` `+` `str``(test_list))` `# using for loop to iterate through list``for` `i ``in` `range``(``len``(test_list)):``    ``for` `j ``in` `range``(i``+``1``, ``len``(test_list)):``        ``# comparing reverse strings and swapping adjacent elements``        ``if` `test_list[i][::``-``1``] > test_list[j][::``-``1``]:``            ``test_list[i], test_list[j] ``=` `test_list[j], test_list[i]` `# printing result``print``(``"List after sorting on reversed strings : "` `+` `str``(test_list))`

Output

```The original list : ['gfg', 'is', 'best', 'for', 'geeks']
List after sorting on reversed strings : ['gfg', 'for', 'is', 'geeks', 'best']```

Time complexity: O(n^2) where n is the length of the input list.

Auxiliary space: O(1), as we are not using any extra space to store the sorted list.

METHOD 4:Using map() function and reversed() method

APPROACH:.

In this approach, we first reverse each string in the original list using a lambda function and the [::-1] slicing notation. Then, we use the sorted() function to sort the list based on the reversed strings, which we access with a lambda function again. Finally, we extract the original strings by using another lambda function to get the second element in each tuple.

ALGORITHM:

1Define the original list
2.Use map() function and a lambda function to reverse each string in the list
3.Sort the list based on the reversed strings using sorted() function and a lambda function
4.Extract the original strings using another lambda function to get the second element in each tuple
5.Print the sorted list

## Python3

 `# Original list``original_list ``=` `[``'gfg'``, ``'is'``, ``'best'``, ``'for'``, ``'geeks'``]` `# Sort list on reversed strings using map() function and reversed() method``sorted_list ``=` `list``(``map``(``lambda` `x: x[``1``], ``sorted``([(word[::``-``1``], word) ``for` `word ``in` `original_list], reverse``=``False``)))` `# Print sorted list``print``(``"List after sorting on reversed strings:"``, sorted_list)`

Output

```List after sorting on reversed strings: ['gfg', 'for', 'is', 'geeks', 'best']
```

Time Complexity:
The time complexity of this approach is O(n log n) because of the sorting operation.

Space Complexity:
The space complexity of this approach is O(n) because we create a list of tuples to store the reversed strings and their original counterparts.

My Personal Notes arrow_drop_up