If the function to be defined is simple, a return statement can be done and can be defined using a lambda expression,
The syntax for a lambda expression is as follows:
Lambda parameters:expression
Lambda expressions do not contain return statements, and you can use lambda expressions wherever functions are used as parameters or return values, and the benefits of lambda functions are:
- Easy and Handy
- You can not name the function, some places do not need to reuse the function, essentially do not need to give the function to think of a name
The following example 1 takes the function defined by the lambda expression as a parameter to the built-in function filter.
Example 1. To use a lambda function as a parameter
>>> L = [1, 2, 3, 4, 5, 6, 7, 8, 9]>>> low = 3>>> High = 7>>> Filter (lambda x, L=low, H=HIGH:H>X>L), L) [4, 5, 6]
Example 1 directly to the defined lambda function as a parameter to the built-in function filter, you can also assign a lambda function to an identifier, convenient for future calls:
Example 2. Invoking a lambda function
>>> f = lambda x, y, z:x + y-z>>> f (1, 2, 3) 0
Python anonymous function--lambda expression