In Python, if the function body is a separate return expression statement, the developer can choose to replace the function with a special lambda expression form:
Copy Code code as follows:
Lambda parameters:expression
A lambda expression is an anonymous function that corresponds to the normal function of a function body as a single return statement. Note that the lambda syntax does not use the return keyword. The developer can use a lambda expression in any location where the function reference can be used. Lambda expressions are handy when developers want to use a simple function as a parameter or return a value. The following is an example of a parameter that uses a lambda expression as a built-in filter function:
Copy Code code as follows:
Alist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Low = 3
High = 7
Filter (lambda x, L=low, H=high:h>x>l, alist) # returns: [4, 5, 6]
As an alternative, developers can also use a local DEF statement that can be named for a function variable. The developer can then use this name as a parameter or return value. The following is an example of the same filter using a local DEF statement:
Copy Code code as follows:
Alist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
Low = 3
High = 7
def within_bounds (value, L=low, H=high):
return h>value>l filter (Within_bounds, alist) #
Returns: [4, 5, 6]
Because lambda expressions are only occasionally useful, many Python users prefer to use Def, which is more general, and if the developer chooses a more reasonable name for the function, it makes the code more readable.