No Multiline Lambda in Python Why not?
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Introduction
Python intentionally restricts lambdas to a single expression. Guido van Rossum rejected multiline lambdas because they conflict with Python's indentation-based syntax. Embedding an indented block inside an expression creates ambiguity for both the parser and human readers. The design philosophy is that if you need multiple statements, use a def statement. Lambda is for short, inline expressions only.
What Lambda Can Do
Lambda can do anything that fits in a single expression. The limitation is that it cannot contain statements (assignments, loops, try/except, print as a statement in Python 2).
What Lambda Cannot Do
Why Not Allow Multiline Lambda?
1. Indentation Ambiguity
Python uses indentation for blocks. Embedding an indented block inside an expression creates parsing ambiguity:
2. Guido's Explicit Rejection
Guido van Rossum has stated multiple times that multiline lambda would damage Python's readability. From his blog:
"Any solution to make lambda multiline would be at best a kludge... I find any solution unacceptable that embeds an indentation-based block in the middle of an expression."
3. def Already Solves This
A named function with def is always clearer than a multiline anonymous function.
Workarounds
Chained Expressions
Walrus Operator (Python 3.8+)
This works but is hard to read. A def is almost always better.
Helper Functions
Conditional Logic
Dictionary Dispatch
When to Use Lambda
Lambda vs def Comparison
Named functions produce better error messages and are easier to debug.
Common Pitfalls
- Assigning lambda to a variable:
square = lambda x: x ** 2is functionally identical todef square(x): return x ** 2but with worse tracebacks. PEP 8 says: "Always use a def statement instead of an assignment statement that binds a lambda expression directly to an identifier." - Late binding in loops:
[lambda: i for i in range(5)]creates 5 lambdas that all return 4 (the final value ofi). Fix:[lambda i=i: i for i in range(5)]captures the current value. - Readability over cleverness: Walrus operator tricks and tuple indexing make lambda do more but hurt readability. If you need a workaround, use
def. - Type annotations: Lambda does not support type hints. Use
defwhen type annotations matter for documentation or static analysis. - Closures and mutable state: Lambda captures variables by reference, not by value. If the variable changes after the lambda is created, the lambda sees the new value.
Summary
- Python lambdas are restricted to a single expression by design
- Multiline lambda conflicts with Python's indentation-based block syntax
- Use
deffor any function that needs multiple statements. It is clearer and produces better error messages - The walrus operator and chained expressions extend what a single expression can do, but
defis almost always more readable - Lambda is best for short, throwaway functions passed as arguments to
sorted(),map(),filter(), and callbacks - PEP 8 discourages assigning lambdas to variables. Use
definstead
Related reading
- Non-alphanumeric list order from os.listdir
- Normal arguments vs. keyword arguments
- Normalized Cross-Correlation in Python
- Not able to import tensorflow_datasets module in jupyter notebook
- not None test in Python
- not None test in Python
- NotFittedError TfidfVectorizer - Vocabulary wasn't fitted
- NotImplementedError Cannot convert a symbolic Tensor 2nd_target0 to a numpy array
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.