How do lambda expressions and inline functions work in Python?
· Category: Python Programming
Short answer
A lambda is a small, anonymous function defined with the lambda keyword. It can take any number of arguments but must contain a single expression. Lambdas are often used as short callbacks.
Steps
- Write
lambda arguments: expression. - Assign to a variable or pass directly to a function.
square = lambda x: x ** 2
print(square(5)) # 25
# Used directly
pairs = [(1, "one"), (2, "two"), (3, "three")]
pairs.sort(key=lambda pair: pair[1])
print(pairs)
Tips
- Lambdas are expressions, so they can be used where
defstatements cannot (e.g., inside a list literal). - For anything more complex than a single expression, use a named function with
deffor readability. functools.partialis often a clearer alternative to lambdas that fix some arguments.
from functools import partial
def power(base, exponent):
return base ** exponent
square = partial(power, exponent=2)
print(square(4)) # 16
Common issues
- Lambdas capture variables by reference, not by value, which can cause late-binding surprises in loops.
- You cannot include statements (like
returnorraise) inside a lambda. - Debugging lambdas is harder because they appear as
<lambda>in tracebacks.