Interview frequency: …
Short answer
Use lambda for a small expression passed directly as an argument (such as key in sorted), and use def for any logic that needs a name, more than one expression, documentation or tests.
Explanation
A lambda is limited to a single expression and does not support statements such as try or plain assignment. Assigning a lambda to a variable (f = lambda x: ...) is discouraged by the style guide (PEP 8) because def is clearer and gives a useful name in tracebacks. operator.itemgetter and attrgetter are often a clearer and faster alternative for extracting fields.
Code example
from operator import attrgetter
users.sort(key=lambda u: (u.last_name, u.first_name))
users.sort(key=attrgetter("created_at"))
# Instead of: is_adult = lambda u: u.age >= 18
def is_adult(user) -> bool:
return user.age >= 18Common mistakes
- Assigning a lambda to a name instead of defining a function with def.
- Writing nested, complicated lambdas that are hard to read and debug.