- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python – Sort by Rear Character in Strings List
When it is required to sort the list by rear character, a method is defined that uses negative indexing to return the result.
Example
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)
Output
The list is : ['python', 'is', 'fun', 'to', 'learn'] The result is : ['python', 'fun', 'learn', 'to', 'is']
Explanation
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.
Advertisements