071. Lambda Functions
Inline anonymous functions for short transformations
071. Lambda Functions
The RAM manager shows every process β but the list is unsorted. He wants the top memory hogs at the top.
He tries to sort the process list by RSS memory. A def comparator seems like overkill for one line. A classmate shows him lambda:
processes = [
{"name": "chrome", "rss_mb": 420},
{"name": "python", "rss_mb": 85},
{"name": "slack", "rss_mb": 310},
]
# Sort largest-first by RSS
top = sorted(processes, key=lambda p: p["rss_mb"], reverse=True)
# β chrome (420), slack (310), python (85)He also adds a quick MB-to-GB converter for the summary line:
mb_to_gb = lambda mb: mb / 1024
print(f"Total: {mb_to_gb(2048):.1f} GB") # β Total: 2.0 GBπ‘ Rule of thumb: Use
lambdawhen the function fits in one expression and you only need it once (as akey=, callback, or one-liner transform). Usedeffor anything longer, recursive, or reused.
Learning objectives
- Create lambda functions for simple transformations
- Use lambda as key= argument in sorted()
- Recognize when lambda is appropriate vs def
Key concepts
- lambda
- anonymous function
- higher-order functions
Try it
Concept detail
lambda creates a small anonymous function in a single expression.
lambda x: x * 2 # equivalent to: def f(x): return x * 2
lambda a, b: a + b # two parameters
lambda p: p["score"] # key function for sorted/min/maxSyntax: lambda Common uses: Lambdas cannot contain: WHY lambdas exist: passing short functions as arguments without the verbosity of a full def. sorted(items, key=lambda x: x[βscoreβ]) reads like a sentence. Use lambdas sparingly β a named def is clearer for anything non-trivial or reused.Solution
double = lambda x: x * 2
to_celsius = lambda f: (f - 32) * 5 / 9
players = [
{"name": "Alice", "score": 95},
{"name": "Bob", "score": 78},
{"name": "Carol", "score": 88},
]
ranked = sorted(players, key=lambda p: p["score"], reverse=True)Tests
def test_double():
assert double(5) == 10
assert double(3) == 6
assert double(0) == 0
def test_to_celsius_freezing():
assert abs(to_celsius(32) - 0.0) < 0.001
def test_to_celsius_boiling():
assert abs(to_celsius(212) - 100.0) < 0.001
def test_to_celsius_body():
assert abs(to_celsius(98.6) - 37.0) < 0.1
def test_ranked_first():
assert ranked[0]["name"] == "Alice"
def test_ranked_last():
assert ranked[-1]["name"] == "Bob"Resources