Use of lambda expressions in python basics
- 2020-04-02 13:23:39
- OfStack
In Python, if the function body is a separate return expression statement, developers can choose to replace the function with a special lambda expression form:
lambda parameters: expression
Lambda expressions are equivalent to anonymous functions of ordinary functions whose body is a single return statement. Note that lambda syntax does not use the return keyword. Developers can use lambda expressions wherever they can use function references. Lambda expressions are handy when a developer wants to use a simple function as an argument or return a value. Here is an example of using a lambda expression as an argument to the built-in filter function:
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 name a function variable. The developer can then use this name as a parameter or return value. Here is an example of the same filter using the local def statement:
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 generic and makes the code more readable if the developer chooses a reasonable name for the function.