`lambda`
lambda creates a small anonymous function from a single expression. It is a shorthand for a def you would otherwise write only to pass it as a callback.
Detailed Explanation
lambda n: n * 2 is a function. It has no name unless you assign one. It takes parameters the same way def does, including defaults, *args, and **kwargs. Its body is one expression, whose value is returned. There is no return keyword, no statements, no annotations, no docstring.
That is the entire feature. lambda exists because Python treats functions as values and some call sites look cleaner with an inline function than with a one-line def above. sorted(users, key=lambda u: u.email) and button.on_click(lambda: save(draft)) are the usual cases.
Anything more complicated belongs in a def. The moment you want a name in a traceback, a guard clause, two expressions, or a comment, lambda is working against you. Style guides that say "no lambda" mean "do not hide logic in an unnamed expression". They do not mean the keyword is deprecated.
Late binding is the common closure trap and it is not unique to lambda, but lambda is where people hit it. funcs = [lambda: n for n in range(3)] then funcs[0]() is 2, because every lambda reads the current n, which is 2 after the loop. The fix is a default argument that binds now: lambda n=n: n.
lambda is an expression, so it can appear where def cannot: inside a list, as a default argument, as a dict value. That flexibility is also how it becomes unreadable. A dict of lambdas that implements a mini language should be a dict of named functions.
There is no typed lambda. If you need annotations, write def. There is no await in a lambda. If you need a coroutine, write async def.
Code Examples
users = [
{"name": "linus", "role": "admin"},
{"name": "ada", "role": "user"},
]
print(sorted(users, key=lambda u: u["name"]))
# [{'name': 'ada', 'role': 'user'}, {'name': 'linus', 'role': 'admin'}]
doubled = list(map(lambda n: n * 2, [1, 2, 3]))
print(doubled) # [2, 4, 6]# Late binding: bind with a default to capture the current n.
wrong = [lambda: n for n in range(3)]
print([fn() for fn in wrong]) # [2, 2, 2]
right = [lambda n=n: n for n in range(3)]
print([fn() for fn in right]) # [0, 1, 2]# Prefer def once there is a name worth saying.
def by_role_then_name(user: dict) -> tuple:
return user["role"], user["name"]
print(sorted(users, key=by_role_then_name))Common Gotchas
Late-binding closures
a lambda inside a loop sees the variable at call time. Capture with `lambda n=n: ...` or use `functools.partial`.
No statements
`lambda x: if x: 1` is a syntax error. Use `def`.
Tracebacks say `<lambda>`
when the callback raises, you lose the function name. Name it if it can fail.
A lambda assigned to a name is a `def` with extra limits
write `def` if you are going to name it anyway.