How to sort with lambda in Python
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.
Introduction
In Python, lambda is commonly used with sorting because it lets you define a small key function inline. Instead of teaching Python how to compare whole objects directly, you tell it which derived value should be used as the sort key for each element.
sorted Versus list.sort
Python gives you two main sorting tools:
- '
sorted(iterable, key=...), which returns a new list,' - '
list.sort(key=...), which sorts the existing list in place.'
Both accept a key function, and lambda is often the shortest way to define that function.
Use sorted when you want to preserve the original sequence. Use list.sort when mutating the list is acceptable.
Sort by a Derived Value
The classic lambda pattern is to transform each element into the value that should drive ordering.
Here Python does not compare the full strings directly. It compares the integer lengths returned by the lambda.
A case-insensitive alphabetical sort works the same way:
Sorting Dictionaries and Objects
Lambda becomes especially useful when the list contains records rather than simple numbers or strings.
For multi-level sorting, return a tuple:
The first tuple element sorts age in ascending order. The second uses a negative score so that larger scores appear first within each age group.
The same idea works for custom objects.
Why the key Parameter Matters
Modern Python sorting is based on key extraction rather than direct comparator functions. That is good for readability and performance because the key for each element is computed once and then reused during sorting.
So when someone says "sort with lambda," what they usually mean is "use a lambda as the key function."
When Lambda Is Not the Best Choice
Lambda is concise, but it is not always the clearest option. If the sort rule becomes long, repeated, or hard to read, switch to a named function.
That usually reads better than a giant inline lambda and gives you a reusable place to document the ordering logic.
Stable Sorting Is Useful Too
Python sorting is stable, which means elements with equal keys keep their original relative order. That can be useful when you perform sorting in multiple passes or when you rely on an earlier ordering as a tie-breaker.
Stable sorting is one reason tuple keys and named key functions work so well in Python.
Common Pitfalls
A common mistake is forgetting that sorted returns a new list while list.sort modifies the original one. That leads to bugs where the caller expects one behavior and gets the other.
Another issue is writing a lambda that assumes every dictionary contains the same keys or every object attribute is non-null. Sorting code often fails on messy data, not on the happy path.
Developers also sometimes make lambda expressions so long that the sort becomes harder to understand than the data itself.
Summary
- Use lambda with the
keyparameter to define custom sort logic inline. - '
sortedreturns a new list, whilelist.sortmutates the original list.' - Lambda keys work well for strings, dictionaries, and custom objects.
- Return tuples from the lambda for multi-level sorting.
- Use a named helper function when the sorting rule stops being small and obvious.
Related reading
- How to specify an Order or Sort using the C driver for MongoDB?
- How to split a string into as few palindromes as possible?
- How to spot a greedy algorithm?
- How to subsample a 2D polygon?
- How to source virtualenv activate in a Bash script
- How to specify a byte-array serializer/deserializer in Kafka-Python
- How to tell if an array is a permutation in On?
- How to tell if greedy algorithm suffices for finding minimum coin change?

DSA Fundamentals
Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Data Structures & Algorithms practice on Codemia
Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.