Given a list of strings, write a program to write sort the list of strings on the basis of last character of each string.
Input:
L = ['ram', 'shyam', 'lakshami']
Output:
['lakshami', 'ram', 'shyam']
Python Code:
L=input().split()
Reverse_String=[]
for i in L:
Reverse_String.append("".join(list(i)[::-1]))
New_SortedList=[]
for i in sorted(Reverse_String):
New_SortedList.append("".join(list(i)[::-1]))
print(New_SortedList,end="")
Explanation:
L=input().split()
- This line takes input from the user as a single line of space-separated strings and splits it into a list of strings. The resulting list is stored in the variableL
.Reverse_String=[]
- This line initializes an empty listReverse_String
that will be used to store the reversed strings.for i in L: Reverse_String.append("".join(list(i)[::-1]))
- This line uses a loop to iterate through each string in the listL
. For each string, it reverses the characters of the string using slicing ([::-1]
), converts the reversed characters back into a string usingjoin()
, and then appends the reversed string to theReverse_String
list.New_SortedList=[]
- This line initializes an empty listNew_SortedList
that will be used to store the sorted list of strings.for i in sorted(Reverse_String): New_SortedList.append("".join(list(i)[::-1]))
- This line uses thesorted()
function to sort theReverse_String
list based on the last character of each string (which is now the first character of the reversed string). For each sorted string, it reverses the characters of the string using slicing ([::-1]
), converts the reversed characters back into a string usingjoin()
, and then appends the original string (not the reversed string) to theNew_SortedList
list.print(New_SortedList,end="")
- This line prints the final sorted list of strings, with theend
parameter set to an empty string to suppress the newline that is normally printed byprint()
.
Overall, the program takes a list of strings, reverses the characters of each string, sorts the list based on the first character of the reversed string (which is the last character of the original string), and then prints the sorted list of strings.