Python Lambda Functions Tutorial
The lambda keyword can be used to create anonymous functions, which are simple functions that do not need to be defined with the def keyword, can take any number of parameters, but can only return the result of a single expression.
Here is the syntax of an anonymous function:
lambda 参数列表: 表达式
The parameter list consists of the function’s arguments separated by commas, while the expression is the function’s return value.
Below is an example of creating an anonymous function using lambda.
# 创建一个匿名函数,接受两个参数并返回它们的和
sum = lambda x, y: x + y
# 调用匿名函数
result = sum(3, 4)
print(result) # 输出:7
In the example above, we defined an anonymous function using lambda x, y. This function takes two parameters, x and y, and returns their sum. We called the anonymous function with sum(3, 4) and assigned the result to the variable result. Finally, we printed the value of result, which is 7.