How to Use a Lambda Sort Key in Python

Sort a list of strings by length, then alphabetically, using a lambda function as the sorting key in Python.

Easy Python 3.6+ Aug 9, 2026 Functions & basics 15 views 0 copies

Python code

10 lines
Python 3.6+
def sort_words(words):
    """Sort words by length, then alphabetically using a lambda key."""
    return sorted(words, key=lambda word: (len(word), word))

if __name__ == "__main__":
    sample_words = ["apple", "kiwi", "banana", "fig", "cherry"]
    result = sort_words(sample_words)
    
    print("Original:", sample_words)
    print("Sorted:", result)

Output

stdout
Original: ['apple', 'kiwi', 'banana', 'fig', 'cherry']
Sorted: ['fig', 'kiwi', 'apple', 'cherry', 'banana']

How it works

The sorted function accepts a key parameter that transforms each element before comparison. Here, the lambda lambda word: (len(word), word) returns a tuple where the first element is the word's length and the second is the word itself. Python compares tuples element-by-element, so it first sorts by length, then breaks ties alphabetically. This approach is concise and avoids defining a separate named function when the logic is short.

Common mistakes

  • Forgetting to include `word` in the tuple, which makes the sort unstable for equal lengths.
  • Using `list.sort()` instead of `sorted()` when you need to preserve the original list.
  • Misplacing parentheses in the lambda, leading to a syntax error.

Variations

  1. Use `lst.sort(key=lambda x: (len(x), x))` to sort the list in-place.
  2. Define a named function `def sort_key(word): return (len(word), word)` and pass it to `sorted()`.

Real-world use cases

  • Sorting file names by extension then name in a directory listing.
  • Ranking players by score, then by name, for a leaderboard display.
  • Ordering search results by relevance, then by title, for consistent presentation.

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.