Python Lambda Expressions
Learn how Python lambda expressions create small anonymous functions, where they fit, and when def is clearer.
Intermediate
A lambda expression creates a small anonymous function. It is useful when you need a function object for a short piece of behavior and do not need to give that function a separate name.
Lambda syntax
The basic form is lambda parameters: expression. The expression is evaluated when the resulting function is called, and its value becomes the function's return value. A lambda can have parameters, but its body is one expression rather than a block of statements.
double = lambda value: value * 2
print(double(5))Lambda functions are function objects
A lambda produces a function object, so you can assign it to a name, call it, or pass it where another function is expected. Assigning a lambda to a name works, but a def statement is usually clearer when the function needs a meaningful reusable name.
add = lambda left, right: left + right
print(add(3, 4))
print(type(add).__name__)Use a lambda as a small argument
A common use is passing a short function directly to another operation. For example, list.sort() accepts a key function. The lambda can express the sorting rule without creating a separately named function.
pairs = [(1, "one"), (2, "two"), (3, "three")]
pairs.sort(key=lambda pair: pair[1])
print(pairs)Lambdas can use surrounding names
Like a nested function, a lambda can refer to a name from its containing scope. This lets a function factory return a small function that remembers the value from the surrounding scope.
def make_multiplier(factor):
return lambda value: value * factor
triple = make_multiplier(3)
print(triple(7))A lambda has one expression
The body of a lambda is restricted to a single expression. It cannot contain statements or annotations. If the operation needs multiple statements or a more descriptive interface, use def instead.
is_long = lambda word: len(word) > 5
print(is_long("Python"))
print(is_long("code"))Choosing lambda or def
Use a lambda when a short function is needed inline and the expression remains easy to read. Prefer def when the function deserves a name, needs multiple statements, or needs annotations. Lambda is a concise form for a limited kind of function, not a separate kind of callable.
words = ["pear", "banana", "fig", "apple"]
words.sort(key=lambda word: len(word))
print(words)Key takeaways
- lambda parameters: expression creates an anonymous function object.
- A lambda body is restricted to one expression; it cannot contain statements or annotations.
- Lambdas can be passed directly where a function object is expected, such as a sorting key function.
- A lambda can refer to names from its containing scope.
- Use def when a function needs a name, multiple statements, or annotations.
Thanks for your feedback.
Mark this learning resource complete to track your learning progress.