When it is required to sort the list by rear character, a method is defined that uses negative indexing to return the result.
Below is a demonstration of the same −
def get_rear_position(element): return element[-1] my_list = ['python', 'is', 'fun', 'to', 'learn'] print("The list is : ") print(my_list) my_list.sort(key = get_rear_position) print("The result is : ") print(my_list)
The list is : ['python', 'is', 'fun', 'to', 'learn'] The result is : ['python', 'fun', 'learn', 'to', 'is']
A method is defined that takes element of the list as a parameter and returns the last element as output using negative indexing.
A list is defined and displayed on the console.
The list is now sorted using key as the previously defined method.
This is the output that is displayed on the console.