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.
Python code
10 linesdef 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
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
- Use `lst.sort(key=lambda x: (len(x), x))` to sort the list in-place.
- 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
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.