The following is an example of how to declare an anonymous function using Python lambda statements: pythonlambda
The so-called anonymous function does not need to define a function. It is used like an expression and does not need a function name (many times it bothers me). Some simple functions are simple. For example
I need a function that adds two integers, which is usually defined in this way.
def add(x, y): return x + y
The functions I need are well completed, but now I need a function that adds numbers and strings.
def addstr(x, y): return x + str(y)
Once again, I met my requirements, but I suddenly needed two integers to be subtracted. The Division function keeps writing, but lambda anonymous functions can be used directly.
# Add implementation f = lambda x, y: x + yf_str = lambda x, y: x + str (y)
Simplified operations make functions simpler, but the disadvantage is poor maintainability. It is not recommended to use functions that are complex.
Lambda statements are designed to bypass function stack allocation during calling for performance reasons. Its syntax is:
lambda [arg1[, arg2, ... argN]]: expression
The following example describes how to use a lambda Statement (without parameters ).
Python anonymous function lambda example (No parameter) Python
# Def true (): return True # equivalent lambda expression >>> lambda: true <function <lambda> at 0x0000000001e000018> # retain the lambda object to the variable so that it can be called at any time> true = lambda: True> true () true # Use def to define the function method def true (): return True # equivalent lambda expression >>> lambda: true <function <lambda> at 0x0000000001e000018> # retain the lambda object to the variable so that it can be called at any time> true = lambda: True> true () True
Here is another example with parameters.
Python anonymous function lambda example (including parameters) Python
# Def add (x, y): return x + y # Use the lambda expressions lambda x, y: x + y # lambda can also have default values and use the variable length parameter lambda x, y = 2: x + ylambda * z: z # Call the lambda function >>> a = lambda x, y: x + y >>> a (1, 3) 4 >>> B = lambda x, y = 2: x + y >>> B (1) 3 >>> B (1, 3) 4 >>> c = lambda * z: z >>> c (10, 'test') (10, 'test ') # def add (x, y): return x + y # Use the lambda expressions lambda x, y: x + y # lambda can also have default values and use the variable length parameter lambda x, y = 2: x + ylambda * z: z # Call the lambda function >>> a = lambda x, y: x + y >>> a (1, 3) 4 >>> B = lambda x, y = 2: x + y >>> B (1) 3 >>> B (1, 3) 4 >>> c = lambda * z: z >>> c (10, 'test') (10, 'test ')
Does it seem that the code is more concise and readable.