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.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 12 views 0 copies

Python code

8 lines
Python 3.9+
def 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

stdout
['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

  1. Use a named function instead of a lambda for better readability or reuse: `sorted(words, key=get_last_letter)`
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.