1. What Is a Lambda Anonymous Function
A lambda expression is one way to define an anonymous function in Python.
An anonymous function is a function object that is created through an expression and usually does not need to be explicitly bound to a function name.
For example, here is an ordinary function that computes the sum of two numbers:
def add(a, b):
return a + b
print(add(10, 20))
Output:
30
The same functionality using a lambda expression:
add = lambda a, b: a + b
print(add(10, 20))
Output:
30
Both forms create a function object; the difference lies in how it is defined:
defis a statement that defines a named function.lambdais an expression that creates an anonymous function object.- A lambda can be used directly as part of an expression.
- Lambda functions are usually used for simple, short logic.
Note that lambda does not mean the function object never has a name.
For example:
add = lambda a, b: a + b
print(add.__name__)
Output:
<lambda>
Although the function is assigned to the variable add, the name of the function object itself is still <lambda>.
2. Basic Syntax of Lambda
The basic syntax of a lambda is as follows:
lambda parameter_list: expression
Its structure can be broken down into three parts:
| Part | Purpose | Example |
|---|---|---|
lambda |
Create a lambda function | lambda |
| Parameter list | Receive the data passed in by the caller | a, b |
| Expression | Compute the result and use it as the return value | a + b |
For example:
add = lambda a, b: a + b
print(add(3, 5))
Output:
8
Execution process:
- Python encounters the lambda expression.
- It creates a function object.
- It assigns the function object to the name
add. - It calls
add(3, 5). - It binds the arguments to
aandb. - It evaluates the expression
a + b. - It uses the result of the expression as the function's return value.
2.1 A Lambda Has Only One Expression
The most important syntactic restriction on a lambda is that its body can contain only a single expression; unlike an ordinary function, you cannot write an arbitrary number of statements.
Correct example:
square = lambda x: x * x
print(square(5))
Output:
25
The following form is invalid:
# Syntax error
result = lambda x:
print(x)
return x * 2
A lambda cannot directly contain:
- Multiple ordinary statements.
- A
returnstatement. forandwhileloop statements.tryandexceptstatements.- Ordinary assignment statements.
However, the expression itself can use conditional expressions, function calls, comprehensions, and similar syntax.
2.2 A Lambda Automatically Returns the Expression's Result
An ordinary function uses return to explicitly return a result:
def square(x):
return x * x
A lambda, by contrast, automatically uses the value of the expression as its return value:
square = lambda x: x * x
The two have the same effect in terms of return behavior.
If the expression does not produce a meaningful result, the actual result of the expression is still returned. For example:
print_result = lambda x: print(x)
result = print_result("Hello")
print(result)
Output:
Hello
None
This is because the print() function itself returns None, so the lambda returns None as well.
III. Parameter Rules for Lambdas
Lambda parameter rules are basically the same as those for regular functions: positional parameters, default parameters, keyword parameters, variable positional parameters, and variable keyword parameters are all supported.
3.1 Lambda with No Parameters
A lambda can take no parameters at all:
get_message = lambda: "Hello Python"
print(get_message())
Output:
Hello Python
3.2 A Single Parameter
square = lambda x: x ** 2
print(square(6))
Output:
36
3.3 Multiple Parameters
add = lambda a, b: a + b
print(add(10, 20))
Output:
30
The number of parameters can be determined according to actual needs:
calculate = lambda a, b, c: a + b * c
print(calculate(2, 3, 4))
Output:
14
3.4 Default Parameters
Lambdas support default parameters:
power = lambda x, n=2: x ** n
print(power(3))
print(power(3, 3))
Output:
9
27
Their default parameter behavior is the same as that of regular functions.
3.5 Variable Positional Parameters
A lambda can use *args to accept any number of positional parameters:
add_all = lambda *args: sum(args)
print(add_all(1, 2, 3))
print(add_all(10, 20, 30, 40))
Output:
6
100
3.6 Variable Keyword Parameters
Lambdas also support **kwargs:
get_keys = lambda **kwargs: list(kwargs.keys())
print(get_keys(name="Python", version=3.14))
Output:
['name', 'version']
3.7 Combining Parameters
calculate = lambda x, y=10, *args, **kwargs: (
x + y + sum(args) + sum(kwargs.values())
)
print(calculate(1, 2, 3, 4, a=5, b=6))
Output:
21
The parameter binding rules here are the same as for regular functions:
xtakes the first positional parameter.ytakes the second positional parameter.argstakes the remaining positional parameters.kwargstakes the extra keyword parameters.
IV. Conditional Expressions in Lambdas
A lambda cannot directly contain multiple if statements, but it can use conditional expressions to implement simple branching logic.
The syntax of a conditional expression:
expression1 if condition else expression2
For example:
check = lambda x: "positive" if x > 0 else "non-positive"
print(check(10))
print(check(-5))
Output:
positive
non-positive
4.1 Multi-Branch Conditional Expressions
Conditional expressions can be nested:
classify = lambda score: (
"Excellent" if score >= 90
else "Good" if score >= 80
else "Pass" if score >= 60
else "Fail"
)
print(classify(95))
print(classify(85))
print(classify(70))
print(classify(50))
Output:
Excellent
Good
Pass
Fail
Although this syntax is legal, readability decreases when there are many conditions.
If the business logic involves complex conditionals, it is recommended to use a regular function:
def classify(score):
if score >= 90:
return "优秀"
elif score >= 80:
return "良好"
elif score >= 60:
return "及格"
else:
return "不及格"
In engineering practice, Lambda should be prioritized for simple expressions, and readability should not be sacrificed just to reduce the number of lines of code.
5. Differences Between Lambda and Regular Functions
Both Lambda and regular functions can ultimately create function objects, but they differ in syntactic capabilities, readability, and applicable scenarios.
| Comparison Dimension | Lambda | Regular Function |
|---|---|---|
| Definition method | lambda expression |
def statement |
| Whether naming is required | Does not require explicit naming | Usually called by name |
| Function body | Single expression | Can contain multiple statements |
| Return result | Automatically returns the expression result | Usually uses return |
| Docstring | Cannot directly write a function-body docstring like a regular function | Supports docstrings |
| Type annotations | Does not support annotation syntax for regular parameters and return values | Supports complete function annotations |
| Decorators | Cannot directly use the def-style decorator syntax |
Supports decorators |
| Debugging capability | Usually weaker; the function name often appears as <lambda> |
Can use meaningful function names |
| Applicable scenarios | Simple, short function logic | Complex, reusable business logic |
5.1 Equivalent Examples of the Two Kinds of Functions
Regular function:
def multiply(a, b):
return a * b
Lambda:
multiply = lambda a, b: a * b
Both can:
- Be called.
- Be passed as arguments.
- Be returned as return values.
- Be referenced by other variables.
- Use outer variables in closures.
Therefore, Lambda is not a completely different function type, but another syntactic form for creating function objects.
5.2 Lambda Can Also Use Function Attributes
Function objects created by Lambda also have the basic attributes of function objects:
add = lambda a, b: a + b
print(add.__name__)
print(add.__module__)
print(add.__defaults__)
print(add.__code__)
These attributes can help you understand the function-object nature of Lambda.
However, the __name__ of a Lambda is usually <lambda>, which is less intuitive than a regular function with a clear name in logs, exception stack traces, and debugging scenarios of complex programs.
6. Lambda and Higher-Order Functions
One of the most common use cases for Lambda is working with higher-order functions.
A higher-order function is a function that meets either of the following conditions:
- It accepts other functions as parameters.
- It returns a function object as its return value.
For example:
def execute(func, value):
return func(value)
result = execute(lambda x: x * 2, 10)
print(result)
Output:
20
Here:
executeis a higher-order function.lambda x: x * 2is the function object passed in.executecalls this function and returns the calculation result.
Lambda can be written directly in a function call without the need to define an extra function name.
6.1 Lambda and map
map() is used to apply a function to each element in an iterable.
Syntax:
map(function, iterable)
For example:
numbers = [1, 2, 3, 4, 5]
result = map(lambda x: x * 2, numbers)
print(list(result))
Output:
[2, 4, 6, 8, 10]
Execution process:
flowchart TD
A["Original list"] --> B["map receives function and iterable"]
B --> C["Get elements one by one"]
C --> D["Call Lambda function"]
D --> E["Produce transformed result"]
E --> F{"Are there more elements?"}
F -->|Yes| C
F -->|No| G["Get map iterator"]
G --> H["Convert to list"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note that in Python 3, map() returns a lazy iterator, and the transformation logic is executed step by step only during iteration.
6.2 Lambda and filter
filter() is used to filter elements in an iterable based on a condition.
Syntax:
filter(function, iterable)
For example, filter even numbers:
numbers = [1, 2, 3, 4, 5, 6]
result = filter(lambda x: x % 2 == 0, numbers)
print(list(result))
Output:
[2, 4, 6]
The result returned by the Lambda is used for a truthiness check:
- If the result is truthy, keep the current element.
- If the result is falsy, filter out the current element.
You can also filter data that meets other conditions:
users = [
{"name": "Alice", "age": 18},
{"name": "Bob", "age": 25},
{"name": "Tom", "age": 16}
]
adults = filter(lambda user: user["age"] >= 18, users)
print(list(adults))
Output:
[{'name': 'Alice', 'age': 18}, {'name': 'Bob', 'age': 25}]
6.3 Lambda and sorted
sorted() can specify the sorting criterion via the key parameter.
key accepts a function, and this function is responsible for extracting the value used for comparison from each element.
For example:
users = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 18},
{"name": "Tom", "age": 30}
]
result = sorted(users, key=lambda user: user["age"])
print(result)
Output:
[
{'name': 'Bob', 'age': 18},
{'name': 'Alice', 'age': 25},
{'name': 'Tom', 'age': 30}
]
Sort by age in descending order:
result = sorted(
users,
key=lambda user: user["age"],
reverse=True
)
The Lambda is responsible for extracting the sort key, while the sorting algorithm is handled by sorted().
6.4 Lambda and max, min
max() and min() also support the key parameter.
Output:
```text {'name': 'Tom', 'age': 30} {'name': 'Bob', 'age': 18} ```6.5 Lambda and reduce
reduce() applies a binary function consecutively to the elements of an iterable, gradually producing a single final result.
It lives in the functools module.
Output:
```text 15 ```The computation proceeds as follows:
```text ((((1 + 2) + 3) + 4) + 5) ```If an initial value is specified:
```python result = reduce(lambda x, y: x + y, [1, 2, 3], 10) print(result) ```Output:
```text 16 ```The calculation starts from the initial value 10.
Note that for simple summation you should generally prefer the built-in sum(); there is no need to force yourself to use reduce() just for the sake of using a Lambda.
7. Practical Applications of Lambda and Sorting
In real-world development, Lambda is often used for sorting complex data structures.
7.1 Sorting by a Specified Position in a Tuple
```python students = [ ("Alice", 85), ("Bob", 92), ("Tom", 78) ] result = sorted(students, key=lambda student: student[1]) print(result) ```Output:
```text [('Tom', 78), ('Alice', 85), ('Bob', 92)] ```Here student[1] refers to the score in the tuple.