Lambda Functions
Lambda Functions
Section titled โLambda FunctionsโA lambda is an anonymous, single-expression function. Itโs useful for short, throwaway functions โ especially as arguments to map, filter, sorted, etc.
lambda arguments: expressionBasic Examples
Section titled โBasic Examplesโsquare = lambda x: x ** 2print(square(5)) # 25
add = lambda a, b: a + bprint(add(3, 4)) # 7
greet = lambda name: f"Hello, {name}!"print(greet("Alice")) # Hello, Alice!With sorted()
Section titled โWith sorted()โpeople = [("Alice", 30), ("Bob", 25), ("Charlie", 35)]
# Sort by agesorted_people = sorted(people, key=lambda p: p[1])# [('Bob', 25), ('Alice', 30), ('Charlie', 35)]
# Sort dicts by valuescores = {"Alice": 90, "Bob": 75, "Charlie": 85}sorted_scores = sorted(scores.items(), key=lambda x: x[1], reverse=True)With map()
Section titled โWith map()โnums = [1, 2, 3, 4, 5]squares = list(map(lambda x: x ** 2, nums))# [1, 4, 9, 16, 25]With filter()
Section titled โWith filter()โnums = [1, 2, 3, 4, 5, 6]evens = list(filter(lambda x: x % 2 == 0, nums))# [2, 4, 6]With reduce()
Section titled โWith reduce()โfrom functools import reduce
nums = [1, 2, 3, 4, 5]product = reduce(lambda a, b: a * b, nums)# 120Lambda vs Regular Function
Section titled โLambda vs Regular Functionโ# Lambdadouble = lambda x: x * 2
# Equivalent regular functiondef double(x): return x * 2Use a regular def when:
- The logic spans multiple lines
- You need a docstring
- You need to reuse it in multiple places
- Readability matters more than brevity
Immediately Invoked Lambda
Section titled โImmediately Invoked Lambdaโresult = (lambda x, y: x + y)(3, 4)print(result) # 7Limitations
Section titled โLimitationsโ- Only a single expression โ no statements, no
if/elseblocks (ternary is OK) - No
returnkeyword - No type annotations
- Harder to debug (shows as
<lambda>in tracebacks)
# Ternary in lambda is fineclassify = lambda x: "even" if x % 2 == 0 else "odd"print(classify(4)) # even