Lambda functions are small, anonymous functions declared inline using the lambda keyword. They are restricted to a single expression whose evaluation result is automatically returned.
flowchart LR
subgraph Standard Function
def["def add(x, y):"] --> ret["return x + y"]
end
subgraph Lambda Expression
lam["lambda x, y: x + y"]
end
lambda arguments: expressionreturn statements.sorted(), map(), filter(), or min()/max().from typing import List, Dict, Any
def Higher_order_demo() -> None:
users: List[Dict[str, Any]] = [
{"name": "Alice", "age": 28, "score": 92},
{"name": "Bob", "age": 34, "score": 85},
{"name": "Charlie", "age": 22, "score": 98},
]
# Sort users by age using lambda
users_by_age = sorted(users, key=lambda u: u["age"])
print("Sorted by Age:", [u["name"] for u in users_by_age])
# Sort users by score descending using lambda
users_by_score = sorted(users, key=lambda u: u["score"], reverse=True)
print("Top Scorers:", [f"{u['name']} ({u['score']})" for u in users_by_score])
# Filtering with lambda and filter()
high_scorers = list(filter(lambda u: u["score"] > 90, users))
print("High Scorers (> 90):", [u["name"] for u in high_scorers])
if __name__ == "__main__":
Higher_order_demo()
add = lambda x, y: x + y. Use standard def add(x, y): return x + y for better stack trace debugging.map()/filter(): [u for u in users if u['score'] > 90] is cleaner than list(filter(lambda u: ..., users)).Sort a list of strings ["apple", "banana", "kiwi", "fig"] by string length using sorted() and a lambda key function.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With