How to Use a Lambda Sorting Key in Python
Sort a list of strings by their last letter using a lambda function as the sorting key.
Python code
8 linesdef get_last_letter(word):
return word[-1]
words = ["banana", "apple", "cherry", "date", "elderberry"]
if __name__ == "__main__":
sorted_words = sorted(words, key=get_last_letter)
print(sorted_words)
Output
['banana', 'apple', 'cherry', 'date', 'elderberry']
['banana', 'apple', 'cherry', 'date', 'elderberry']
How it works
The sorted() function accepts a key parameter that specifies a function to extract a comparison key from each element. Here, the lambda function lambda w: w[-1] returns the last character of each word, and sorted() orders the list based on these keys. This approach is more concise and inline than defining a separate named function like get_last_letter. The key function is called once for each item, so performance is efficient even for larger lists.
Common mistakes
- Forgetting to include `key=` when passing the lambda to `sorted()`
- Using `reverse=True` when the requirement is opposite sorting order
- Confusing `sorted()` (returns a new list) with `list.sort()` (modifies in place)
Variations
- Use a named function instead of a lambda for better readability or reuse: `sorted(words, key=get_last_letter)`
- Sort by multiple criteria using a tuple key: `sorted(words, key=lambda w: (len(w), w[-1]))`
Real-world use cases
- Sorting customer names by their last character in a UI list for quick alphabetical grouping.
- Ordering log lines by the final status code in a batch processing script.
- Sorting product codes by their suffix to group items with similar variants in an inventory report.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.