Lambda, map, filter and sorted
Functions are values you can hand to other functions. Watch sorted() rank search results with key=lambda, then see filter and map do the same job a comprehension does.
In Python a function is a value. You can store it in a variable, put it in a list, or pass it to another function. A function that takes another function as an argument is called a higher-order function, and three of them are everywhere in agent code: sorted(), filter() and map().
The pattern you will use most is sorted(items, key=...). The key is a function that sorted() calls once per item to get the value it should compare. Sort search hits by their score, tickets by priority, messages by timestamp: it is always the same key= trick.
When the key function is one line and used once, you can write it inline with lambda. lambda r: r["score"] is a function with no name that takes r and returns r["score"]. That is the whole of lambda: syntactic sugar for a tiny def.
Press Run to execute rank_results.py. The program ranks a support agent’s search results, first with a named function, then with a lambda, then filters and maps them, and finally does the same with a comprehension.
# Rank search results for a support agent, passing functions as values.
results = [
{"title": "Reset UPI PIN", "score": 0.62},
{"title": "UPI payment failed", "score": 0.91},
{"title": "Change registered mobile", "score": 0.35},
{"title": "UPI daily limit", "score": 0.78},
]
def by_score(result):
return result["score"]
ranked = sorted(results, key=by_score, reverse=True)
print("Top:", ranked[0]["title"])
# Same thing with a lambda: a one-line function with no name.
ranked = sorted(results, key=lambda r: r["score"], reverse=True)
print("Top again:", ranked[0]["title"])
# filter keeps the items for which the function returns True.
good = list(filter(lambda r: r["score"] >= 0.6, results))
print("Good enough:", len(good))
# map applies a function to every item.
titles = list(map(lambda r: r["title"], good))
print("Titles:", titles)
# The same two steps as one comprehension. Most Python code prefers this.
titles = [r["title"] for r in results if r["score"] >= 0.6]
print("Same:", titles)Press Play to run the program line by line, or step with ← →.
Variables
Nothing defined yet.
Output
Nothing printed yet.
What to notice
- Pass the function, don’t call it.
key=by_scorehands the function over;key=by_score()would call it with no arguments and fail. No brackets means “the function itself”. - The key is computed once per item.
sorted()asksby_scorefor each item’s key, then compares the keys. The dicts themselves are never compared, so there is no error about comparing dicts. sorted()returns a new list;list.sort()changes the list in place and returnsNone.ranked = results.sort(...)is a classic bug that leavesrankedasNone.reverse=Truegives descending order and keeps ties in their original order. Python’s sort is stable, so items with equal scores stay in the order they arrived.filter()andmap()return lazy iterators. Wrap them inlist()when you want to see or index the items. A comprehension[r["title"] for r in results if r["score"] >= 0.6]does both jobs in one readable line, and most Python code prefers it.- A lambda is limited to one expression. No statements, no loops, no assignment. If you need more, write a
defand give it a name.
Why this matters for AI work
Agent code is full of small ranking and selection steps: pick the top retrieved chunks, keep the tool calls that succeeded, pull the text field out of each event. You will read sorted(hits, key=lambda h: h.score, reverse=True) in retrieval code and max(candidates, key=...) in evaluation code. Knowing that key= receives one item and returns something comparable lets you read, and fix, those lines with confidence.