Python · The language, not just syntax
When should you use a lambda?
Short answer
A lambda is an anonymous function limited to a single expression. It is best for short throwaway callbacks such as a sort key, and should not replace a named def for anything non-trivial.
A lambda has the same semantics as a def but no name and no statement body. It is useful precisely where a tiny function is passed inline and naming it would add noise, especially as the key argument to sorted, min or max.
records = [
{"name": "Asha", "score": 91},
{"name": "Ravi", "score": 78},
]
ranked = sorted(records, key=lambda record: record["score"], reverse=True)
print(ranked[0]["name"])
format_price = lambda cents: str(round(cents / 100, 2))
print(format_price(1999))Limits and guidance
- A lambda cannot contain statements, assignments or annotations
- A lambda's body is a single expression, so tracebacks and debugging are less clear
- Use operator.itemgetter or attrgetter instead of a lambda when one fits
- Lambdas are not faster than def; the difference is only syntax
If a lambda is assigned to a variable, grows beyond one short expression or needs a docstring, it should be a def. Named functions give useful __name__ values in profiles and tracebacks, which matters during incident response.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What can a lambda not do that a def can?
- 2Why might a lambda be harder to debug?
- 3When would itemgetter be better than a lambda?
- 4Does a lambda create a closure?
Say it in the interview
A lambda is an anonymous single-expression function, and I use it for short inline callbacks such as sort keys. Anything that needs statements, a docstring or a name should be a def, because named functions give better tracebacks and profiles. I also prefer operator.itemgetter when it fits. Lambdas capture by reference, so I bind loop values explicitly when needed.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.