Lambda expressions are equivalent to an anonymous function of a common function whose function body is a single return statement. This article describes how to use lambda expressions in Python. if the function body is a separate return expression statement, developers can replace the function with a special lambda expression:
The code is as follows:
Lambda parameters: expression
A lambda expression is equivalent to an anonymous function of a common function whose function body is a single return statement. Note that the return keyword is not used in lambda syntax. Developers can use lambda expressions wherever function references are available. Lambda expressions are convenient when developers want to use a simple function as a parameter or return value. The following is an example of using a lambda expression as a parameter of the built-in filter function:
The code is 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 another option, developers can also use a local def statement that can name function variables. Then, developers can use this name as a parameter or return value. The following is an example of the same filter using the local def statement:
The code is 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]
Lambda expressions are only useful occasionally. many Python users prefer def and def to be more generic. if a developer selects a reasonable name for the function, it makes the code more readable.