Lesson · Functions
Lambda Functions
45 min readLambda Functions
Lambda expressions create small anonymous functions from a single expression. They are useful as short key or callback functions, but a named `def` is usually clearer when behavior needs explanation.
Learning goals
- Read a lambda expression and name its parameters, its single expression, and the value it returns.
- Create a function object with
lambdaand call it immediately or store it under a name. - Use a lambda as the
keyargument ofsorted,min, ormax. - Explain why a lambda body cannot contain statements such as assignment or
try. - Decide when a named
defcommunicates intent better than a lambda.
Mental model
A lambda is a def reduced to its essentials: parameters and one expression that doubles as the return value. That restriction is the design, since no statements means no internal state to track, which is why lambdas read well as throwaway key extractors and poorly as anything that needs a name, a docstring, or a second step. The fence follows the example's lambda from definition, through the calls sorted makes, to the reordered list.
A def with the statements removed
one expression is the return value
Mental model
the same mechanism as a compact list
key=lambda row: row["score"]
↑ parameter ↑ the single expression, returned automatically
↓ sorted calls the lambda once per record
98, 99 the extracted values decide the order
↓ reverse=True flips the comparison
[{"name": "Grace", "score": 99}, {"name": "Ada", "score": 98}]Core idea
A lambda is a function object created by an expression instead of a statement: same calling behavior as def, but with a body limited to one expression that is returned automatically, and no room for assignments or control-flow statements. Use it where the behavior is obvious at the call site, most often as a one-line key extractor for sorted, min, or max; the moment the logic needs a name to be understood, promote it to def.
Syntax
A lambda expression is an anonymous function written as lambda parameters: expression. Evaluating it creates a function object, exactly as def does, but the body is one expression whose value is returned automatically. Lambda objects are ordinary callables: they can be stored, passed as arguments, and called later.
Expressions only
A lambda body is exactly one expression, so it cannot contain statements such as assignment statements, try, or while. Complex behavior belongs in a named def.
Sorting keys
A lambda is commonly used as a small key extractor for sorted, min, or max. Prefer a named function when the ordering rule is domain-significant or reused.
Callbacks
A callback is a callable supplied now and invoked later by another component. Document when it runs, what arguments it receives, and how its exceptions are handled.
When normal def is clearer
When normal def is clearer is a design question rather than a syntax rule. Use the mental model from this lesson to identify the conditions, tradeoffs, and failure modes that make one choice appropriate.
Walkthrough
recordsis a list of two dictionaries; the lambda is not called whensortedreceives it, only stored as thekeyargument.key=lambda row: row["score"]creates a one-parameter function whose body indexes each record;sortedcalls it once per element and compares the returned numbers.reverse=Truesorts from largest to smallest, so Grace's 99 lands before Ada's 98 andprintshows the two dictionaries in that order.- Predict before running: what
sorted(records, key=lambda row: row["name"])would produce and which element would move first oncereverse=Trueis removed.
Experiments to try
- Rewrite the key as a named function
def score_of(row): return row["score"]and confirm the sorted output is identical; note what the lambda saved in exchange for the name. - Remove
reverse=Trueand predict the new first element before running; then sort byrow["name"]and by the whole dictionary default and compare the three orders. - Try a statement inside a lambda, for example
lambda row: row["score"] += 1, and read theSyntaxError; move the same logic into adefand watch it work. - Pass the same extractor lambda to
min(records, key=...)andmax(records, key=...)and state which record each call returns and why.
Common mistakes
- Writing statements inside a lambda body, such as assignment or
try: the grammar allows one expression only, so the attempt fails at parse time withSyntaxError. - Letting a lambda outgrow one line: a long or nested lambda hides control flow that a named
defwould document, and tracebacks then show<lambda>instead of a meaningful function name. - Assuming a lambda's body runs when the lambda is created: it runs on every call, so a lambda that reads a captured variable sees the value current at call time, not the value from definition time.
- Calling
sorted(records)without akeywhen the elements are dictionaries: there is no ordering between dictionaries, so the call raisesTypeErrorinstead of guessing which field to compare.
Practice: Easy
- Run the worked example and write down the order of names; then delete
reverse=True, rerun, and explain which comparison flipped. - Replace the lambda with
def score_of(row): return row["score"]and confirm the output is unchanged; name one thing the named version can do that the lambda cannot. - Assign
score_of = lambda row: row["score"], callscore_of(records[0]), and check whatscore_of.__name__shows.
Practice: Medium
- Write a single key expression that sorts by score descending and breaks ties by name ascending; test it on records with equal scores.
- Pass the same extractor lambda to
min,max, andsortedand confirm the three results agree on the best and worst records. - Build a key factory,
def sc(key): return lambda row: row[key], callsorted(records, key=sc("name")), and explain what the outer function returns.
Practice: Hard
- Design a
rank(records, by)helper wherebyis a key callable chosen by the caller; define what happens for a callable that raises, and test it with at least three different key functions. - Build a loop trap: create a list of lambdas inside a
forloop that each capture the loop variable, call them all, and watch them agree; then repair the capture with a default parameter such aslambda row, i=i: ...and explain when each value is bound. - Trigger the same exception inside a lambda and inside an equivalent
def; paste both tracebacks, list two debugging advantages of the named version, and one case where the lambda still reads better at the call site.
Lesson checklist
- I can read
lambda row: row["score"]and name its parameter, its expression, and its automatic return. - I can use a lambda as the
keyofsorted,min, andmax. - I can say why statements cannot appear in a lambda body.
- I can move a lambda into a
defwhen it needs a name, a docstring, or more than one expression.
Remember
A lambda is a `def` compressed to a parameter list and one expression that is returned automatically, which makes it ideal for throwaway key extractors and callbacks passed to functions such as `sorted`. The limits are the point: no statements, one expression, and `<lambda>` in tracebacks, so move the logic to a named function as soon as it needs explaining or reusing.
Interview angles
What is the main purpose of **Syntax**?+
A lambda expression is an anonymous function written as lambda parameters: expression; evaluating it creates a function object, exactly as def does, but its body is one expression whose value is returned automatically. Lambda objects are ordinary callables, so they can be stored, passed as arguments, and called later.
What should you pay attention to when using **Expressions only**?+
A lambda body is exactly one expression, so it cannot contain statements such as assignment statements, try, or while. Complex behavior belongs in a named def.
How does **Sorting keys** fit into this lesson?+
A lambda is commonly used as a small key extractor for sorted, min, or max. Prefer a named function when the ordering rule is domain-significant or reused.
Why do lambdas created in a loop often all behave the same?+
A lambda body runs when the lambda is called, not when it is defined, so every lambda that referenced the loop variable reads that variable's value at call time, which by then is the final one. Bind the current value at definition time with a default parameter, for example lambda row, i=i: ..., to freeze it per lambda.