Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python – Sort by Rear Character in Strings List
When working with string lists in Python, you may need to sort them based on their last character. Python provides multiple approaches to achieve this using the sort() method with a custom key function.
Using a Custom Function
Define a function that returns the last character using negative indexing ?
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']
Using Lambda Function
A more concise approach using lambda function ?
words = ['apple', 'banana', 'cherry', 'date', 'elderberry']
print("Original list:")
print(words)
words.sort(key=lambda x: x[-1])
print("Sorted by last character:")
print(words)
Original list: ['apple', 'banana', 'cherry', 'date', 'elderberry'] Sorted by last character: ['banana', 'apple', 'date', 'elderberry', 'cherry']
Using sorted() Function
Create a new sorted list without modifying the original ?
colors = ['red', 'blue', 'green', 'yellow', 'purple']
print("Original list:")
print(colors)
sorted_colors = sorted(colors, key=lambda x: x[-1])
print("Sorted by last character:")
print(sorted_colors)
print("Original list unchanged:")
print(colors)
Original list: ['red', 'blue', 'green', 'yellow', 'purple'] Sorted by last character: ['blue', 'red', 'green', 'yellow', 'purple'] Original list unchanged: ['red', 'blue', 'green', 'yellow', 'purple']
Comparison
| Method | Modifies Original | Best For |
|---|---|---|
Custom function + sort()
|
Yes | Reusable logic |
Lambda + sort()
|
Yes | Concise one-time use |
Lambda + sorted()
|
No | Preserving original list |
Conclusion
Use lambda functions for concise sorting by last character. Use sorted() when you need to preserve the original list. Custom functions work best for reusable sorting logic.
Advertisements
