Back to Blog
Python

Python Lambda with Sorted: Custom Sorting Made Clear

python lambda with sorted: Learn how to use lambda functions with Python's sorted() to sort lists, dictionaries, and objects by custom keys, with practical examples an...

Pythonlambdasortedsortingkey functioncustom sort
Illustration of a lambda function as a key that sorts a list of items in Python

When you need to sort data by anything other than the natural order of the values, Python's sorted() function lets you pass a key function. A lambda is often the most concise way to define that key function inline. Using python lambda with sorted lets you sort lists, dictionaries, and objects by arbitrary attributes without writing a separate named function.

How the key Parameter Works

The sorted() function accepts a key parameter that is called once for each element before comparison. The function receives an element and returns a value that Python uses for ordering. This is different from a comparison function that returns -1, 0, or 1; the key function transforms each element into a sortable proxy.

words = ["banana", "apple", "cherry", "date"] sorted_by_length = sorted(words, key=lambda w: len(w)) print(sorted_by_length) # ['date', 'apple', 'banana', 'cherry']

The lambda lambda w: len(w) returns the length of each string, so sorted() orders the words by their character count. The original list is unchanged; sorted() always returns a new list.

Sorting Dictionaries and Objects

A common use case is sorting a list of dictionaries by a specific field. The lambda extracts that field from each dictionary.

people = [ {"name": "Alice", "age": 30}, {"name": "Bob", "age": 25}, {"name": "Carol", "age": 35} ] sorted_people = sorted(people, key=lambda p: p["age"]) print(sorted_people) # [{'name': 'Bob', 'age': 25}, {'name': 'Alice', 'age': 30}, {'name': 'Carol', 'age': 35}]

The same pattern works with objects. If you have a class with attributes, the lambda can access them directly.

class Product: def __init__(self, name, price): self.name = name self.price = price products = [Product("Laptop", 1200), Product("Mouse", 25), Product("Keyboard", 80)] cheapest_first = sorted(products, key=lambda p: p.price)

This avoids writing a separate function like def get_price(p): return p.price when you only need the sort key in one place.

Sorting by Multiple Criteria

When you need to sort by one field and then another, you can return a tuple from the lambda. Python compares tuples element by element, so the first element is the primary key and the second is the secondary key.

records = [ {"name": "Alice", "age": 30, "score": 88}, {"name": "Bob", "age": 25, "score": 95}, {"name": "Carol", "age": 30, "score": 92} ] sorted_records = sorted(records, key=lambda r: (r["age"], r["score"]))

Here, records are sorted by age first, and within the same age, by score. To reverse only one criterion, you can negate numeric values or use a custom approach. For strings, you would need to reverse the whole sort or use a wrapper class, but for numeric fields negation works cleanly.

# Sort by age ascending, then by score descending sorted_records = sorted(records, key=lambda r: (r["age"], -r["score"]))

Performance Considerations

The key function is called exactly once per element, and the returned values are cached internally by sorted(). This means the lambda's execution time is added to the overall sort cost, but it does not multiply with the comparison count. For large lists, the overhead of a lambda is usually negligible compared to the O(n log n) comparison phase.

However, if the lambda performs expensive work—such as a database lookup or a complex computation—that cost is paid for every element. In such cases, consider precomputing the keys into a separate list and sorting with zip, or use the key parameter with a named function if the logic is complex enough to need documentation.

# Expensive key computation: avoid if possible sorted_data = sorted(data, key=lambda x: expensive_function(x)) # Better: precompute keys when the list is large and the function is costly keys = [expensive_function(x) for x in data] sorted_pairs = sorted(zip(keys, data)) sorted_data = [item for _, item in sorted_pairs]

The second approach avoids calling expensive_function during the sort itself, but it still calls it once per element. The benefit is that you can reuse the computed keys if you need to sort by the same key multiple times.

Common Mistakes and Edge Cases

One frequent error is forgetting that sorted() returns a new list. If you expect the original list to be modified, use list.sort() instead. The list.sort() method also accepts a key parameter and works in place.

Another issue is using a lambda that references a variable that changes during iteration. Because lambdas capture variables by reference, a lambda inside a loop may see the final value of the loop variable, not the value at the time the lambda was created. This is rarely a problem with sorted() because the key function is called immediately, but it can appear if you build a list of lambdas and use them later.

# This works because the lambda is called immediately items = [(1, 2), (3, 1), (2, 3)] sorted_items = sorted(items, key=lambda x: x[1])

When sorting strings, be aware that Python sorts by Unicode code point by default. If you need case-insensitive sorting, use key=lambda s: s.lower() or str.casefold() for more aggressive normalization.

When to Avoid Lambda in sorted()

A lambda is convenient, but it can hurt readability when the key logic is long or reused in multiple places. If the same key function is needed in several sorts, define a named function. This also makes unit testing easier.

def get_priority(task): return (task["urgent"], task["due_date"]) sorted_tasks = sorted(tasks, key=get_priority)

Also, if the key function requires complex branching or exception handling, a lambda becomes unwieldy. Named functions allow docstrings and type hints, which improve maintainability in a codebase.

For simple, one-off sorts, a lambda keeps the code compact. The decision comes down to whether the lambda remains clear to the next reader. If you find yourself writing a lambda longer than a single line, or with multiple expressions, extract it into a named function.

python lambda with sorted: Practical Usage and Code Examples | RYUSLOG DEV