Python lambda (anonymous function)
Python useslambdato create anonymous functions.
The lambda function is a small, anonymous, inline function that can have any number of parameters, but can only have one expression.
Anonymous functions do not need to usedefthe keyword to define a complete function.
lambda functions are usually used to write simple, one-line functions, often used when a function needs to be passed as a parameter, such as in functions like map(), filter(), reduce(), etc.
Features of lambda functions:
- The lambda function is anonymous; it has no function name, and can only be used by assigning it to a variable or passing it as a parameter to other functions.
- A lambda function usually contains only one line of code, which makes it suitable for writing simple functions.
Lambda syntax format:
lambda arguments: expression
lambdais a Python keyword used to define lambda functions.argumentsis the parameter list, which can contain zero or more parameters, but must be before the colon (:) specified before.expressionis an expression used to compute and return the result of the function.
The following lambda function has no parameters:
Example
The output result is:
Hello, world!
The following example uses lambda to create an anonymous function, sets a function parameter a, the function calculates parameter a plus 10, and returns the result:
Example
The output result is:
15
A lambda function can also have multiple parameters, with parameters separated by commas,separated:
The following example uses lambda to create an anonymous function, the function parameters a and b are multiplied, and the result is returned:
Example
The output result is:
30
The following example uses lambda to create an anonymous function, the function parameters a, b, and c are added, and the result is returned:
Example
The output result is:
13
lambda functions are usually used together with built-in functions such as map(), filter(), and reduce() to perform operations on collections. For example:
Example
The output result is:
[1, 4, 9, 16, 25]
Use lambda function with filter() to filter even numbers:
Example
The output result is:
[2, 4, 6, 8]
The following demonstrates how to use reduce() and a lambda expression to calculate the cumulative product of a sequence:
Example
The output result is:
120
In the above example, the reduce() function iterates over the numbers list and uses the lambda function to continuously update the cumulative result, finally obtaining1 * 2 * 3 * 4 * 5 = 120the result of.
Other extensions