Python Lambda
Write short anonymous functions and use them with sorted, map, and filter.
Why it matters: Ranking chunks by score and sorting model runs by latency usually means key=lambda.
Basics
Lambda
lambda args: expression makes a small function without a name.
It holds one expression only. No loops or assignments.
If the function needs a name, use def. Lambda belongs inline, often as key=.
Tiny example
Use a lambda as a sort key.
chunks = [{"score": 0.4}, {"score": 0.9}]
print(sorted(chunks, key=lambda c: c["score"]))Basics
sorted with key
sorted(iterable, key=..., reverse=...) returns a new list.
The key function runs on each item. Results are compared.
For multi-level sort, return a tuple: key=lambda r: (-r["score"], r["id"]).
Negating a number flips sort direction.
Tiny example
Sort scores from high to low.
scores = [0.4, 0.9, 0.7]
print(sorted(scores, reverse=True))Basics
map and filter
map(fn, iterable) applies a function to each item. filter(fn, iterable) keeps truthy results.
Both return lazy iterators. Wrap with list() to see values.
In modern Python, a comprehension is often clearer: [s for s in scores if s >= 0.7].
Tiny example
Keep high scores with filter.
scores = [0.9, 0.4, 0.8]
print(list(filter(lambda s: s >= 0.7, scores)))Then AI / ML
AI / ML examples
Same idea, used in real AI work. Press Try in lab to run it.
AI / ML example
AI / ML: rank retrieved chunks
Sort by score descending, then pick the best.
In AI / ML: RAG pipelines sort chunks by score before packing the prompt.
example.py
Python
chunks = [
{"id": "c1", "score": 0.71},
{"id": "c3", "score": 0.94},
{"id": "c2", "score": 0.71},
]
ranked = sorted(chunks, key=lambda c: c["score"], reverse=True)
print(ranked)
print("best:", max(chunks, key=lambda c: c["score"])["id"])AI / ML example 2
AI / ML: model leaderboard sort
Sort by accuracy first, then by latency.
In AI / ML: Model comparison tables sort by score, then latency.
example.py
Python
runs = [
{"model": "b", "score": 0.90, "latency": 300},
{"model": "a", "score": 0.90, "latency": 120},
{"model": "c", "score": 0.85, "latency": 100},
]
ranked = sorted(runs, key=lambda r: (-r["score"], r["latency"]))
for r in ranked:
print(r["model"], r["score"], r["latency"])Takeaways
- 1lambda holds one expression and fits well as a key= argument.
- 2sorted with a tuple key does multi-level ranking.
- 3Prefer comprehensions over map/filter when either works.