Python 3 Lambda anonymous function detailed

Source: Internet
Author: User



-------Lambda-------------------------------------



In addition to the DEF statement, Python provides a form of expression that generates a Function object. Because it is very similar to a tool in the Lisp language, it is called a lambda. Just like Def, this expression creates a function that can then be called, but it returns a function instead of assigning the function to a variable name. This is why lambda is sometimes called an anonymous function. In fact, they are often used in the form of a function definition in a row, or as a deferred execution of some code.






Lambda expression



The general form of a lambda is the keyword lambda, followed by one or more parameters (a list of arguments enclosed in parentheses in a Def header and similar), followed by a colon, followed by an expression:



Lambda Argument1,argument2, ... argumentn:expression using argument






The function object returned by the lambda expression works exactly the same as the function object created and copied by Def, but the lambda is a bit different from what makes it useful to play a particular role.





    • A lambda is an expression, not a statement . Because of this, lambda can appear where the DEF is not allowed in the Python syntax-for example, in a list constant or in the parameters of a function call. Also, as an expression, lambda returns a value (a new function) that can optionally be assigned to a variable name. In contrast, the DEF statement always has to assign a new function to a variable name in the head, rather than the function as the result of the return.

    • the body of a lambda is a single expression, not a block of code . The body of the lambda is as simple as the code in the return statement of the Def body. Simply write the result as a smooth expression rather than a definite return. Because it is limited to expressions, lambda is usually less powerful than def: You can only encapsulate limited logic in the body of a lambda, and even statements such as if are not usable. This is intentionally designed-it limits the nesting of programs: Lambda is designed to write simple functions, and DEF is used to handle larger tasks.





In addition to these differences, both def and Lambda can do the same kind of work. For example, we saw how to create a function using DEF statements.

>>> def func (x, y, z): return x + y + z
...
>>> func (2, 3, 4)
9
However, you can use lambda expressions to achieve the same effect, by explicitly assigning the result to a variable name, and then you can call this function by this variable name.

>>> f = lambda x, y, z: x + y + z
>>> f (2, 3, 4)
9
Here f is assigned to a function object created by a lambda expression. This is the task completed by def, but the assignment of def is done automatically.



Default parameters can also be used in lambda parameters, just as they are used in def.

>>> x = (lambda a = "fee", b = "fie", c = "foe": a + b + c)
>>> x ("wee")
‘Weefiefoe’
The code in the body of the lambda, like the code in the def, follows the same rules of search. A local scope introduced by a lambda expression is more like a nested def statement, and it will automatically find the variable name from the upper-level function, the module, and the built-in scope (through the LEGB rule).

>>> def knights ():
... title = "Sir"
... action = (lambda x: title + ‘‘ + x)
... return action
...
>>> act = knight ()
>>> act (‘robin’)
‘Sir robin’
In Python 2.2, the value of the variable name title is usually modified to be passed in by the value of the default parameter.





Why use lambda

Generally speaking, lambda acts as a function of sketching, allowing a function definition to be embedded in the code used. They are completely optional (you can always use def to replace them), but if you only need to embed a small piece of executable code, they will bring a more concise code structure.



For example, we will see the callback handler later, which is often written as a single-line lambda expression in the parameter list of a registration call, rather than using a def defined elsewhere in the file and then referencing That variable name.

Lambda is usually used to write jump tables, that is, lists or dictionaries of actions, which can perform corresponding actions as needed. As shown in the following code.

L = [lambda x: x ** 2,
     lambda x: x ** 3,
     lambda x: x ** 4]

for f in L:
    print (f (2)) # prints 4, 8, 16
    
print (L [0] (3)) # prints 9
When you need to write a small piece of executable code into a place where the def statement cannot be syntactically written, lambda expressions are most useful as a shorthand for def. For example, this code snippet can create a list of three functions by embedding a lambda expression in the list constant. A def will not work in list constants because it is a statement, not an expression. The equivalent def code may require temporary function names and function definitions outside the environment you want to use.

def f1 (x): return x ** 2
def f2 (x): return x ** 3
def f3 (x): return x ** 4

L = [f1, f2, f3]

for f in L:
    print (f (2)) # prints 4, 8, 16
    
print (L [0] (3)) # prints 9
In fact, we can use dictionaries or other data structures in Python to build more kinds of behavior tables to do the same thing. Here is another example given in interactive prompt mode:

>>> key = ‘got’
>>> {‘already’: (lambda: 2 + 2),
... ‘got’: (lambda: 2 * 4),
... ‘one’: (lambda: 2 ** 6)} [key] ()
8
Here, when this dictionary is common to Python, each nested lambda generates and leaves a function that can be called later. One of the functions is retrieved by the key index, and the parentheses cause the removed function to be called. Compared with the extended usage of the if statement shown to you before, writing code like this can make the dictionary a more versatile multi-way branching tool.



If you are not doing this kind of work with lambda, you need to use def statements that have appeared elsewhere in the three files to replace them, that is, you need to define these functions somewhere outside the dictionary that these functions will use.

>>> def f1 (): return 2 + 2
...
>>> def f2 (): return 2 * 4
...
>>> def f3 (): return 2 ** 6
...
>>> key = ‘one’
>>> {‘already’: f1, ‘got‘: f2, ‘one‘: f3} [key] ()
64
Similarly, the same function will be achieved, but def may appear anywhere in the file, even if there is very little code behind them. Similar to the code of lambda just now, it provides a particularly useful function that can appear in a single situation: if the three functions here will not be used elsewhere, it is reasonable to embed them as a lambda in the dictionary. . Not only that, the def format requires the creation of variable names for these small functions. These variable names may conflict with other variable names in this file (may not be, but it is always possible).





How (don't) make Python code obscure

Since the body of the lambda must be an expression (rather than some statements), it can be seen that only limited logic can be encapsulated into a lambda. If you know what you are doing, then you can write enough statements in Python as expression-based equivalents.



For example, if you want to print in a lambda function, write the expression sys.stdout.write (str (x) + "\ n") directly instead of using statements like print (x). Similarly, to escape logic in a lambda, you can use if / else ternary expressions, or equivalent but / or combinations that require some skill. As we learned earlier, the following statement:

if a:
    b
else:
    c
 It can be simulated by the following generalized equivalent expression:

b if a else c
((a and b) or c)
Because such similar expressions can be placed in lambdas, they can implement selection logic in lambda functions.

>>> lower = (lambda x, y: x if x <y else y)
>>> lower (‘bb‘, ‘aa‘)
‘Aa’
>>> lower (‘aa‘, ‘bb‘)
‘Aa’
In addition, if you need to execute a loop in a lambda function, you can embed tools such as map calls or list parsing expressions.

>>> import sys
>>> showall = lambda x: list (map (sys.stdout.write, x))

>>> t = showall ([‘spam \ n‘, ‘toast \ n‘, ‘eggs \ n’])
spam
toast
eggs

>>> showall = lambda x: [sys.stdout.write (line) for line in x] # List parsing
>>> t = showall ([‘spam \ n‘, ‘toast \ n‘, ‘eggs \ n’])
spam
toast
eggs
These techniques must be used only as a last resort. If you are not careful, they can lead to unreadable (and obscure) Python code. In general, conciseness is better than complexity, clarity is better than obscurity, and a complete statement is better than a mysterious expression. This is why lambda is limited to expressions. If you have more responsible code to write, you can use def, lambda for a smaller piece of inline code. On the other hand, you will also find that the use of humidity is very useful.





Nested lambda and scope

Lambda is the biggest beneficiary of nested function scope lookup (E in the LEGB principle). For example, in the following example, the lambda appears in def (a typical case), and when the mall function is called, the nested lambda can get the value of the variable name x in the scope of the upper function.

>>> def action (x):
return (lambda y: x + y)

>>> act = action (99)
>>> act
<function action. <locals>. <lambda> at 0x0000014EF59F4C80>
>>> act (2)
101
The previous discussion about the scope of nested functions did not indicate that the lambda can also obtain the variable name in any upper lambda. This situation is a bit obscure, but imagine if we replaced the high-end def with a lambda in our previous example.

>>> action = (lambda x: (lambda y: x + y))
>>> act = action (99)
>>> act (3)
102
>>> ((lambda x: (lambda y: x + y)) (99)) (4)
103
The nested lambda structure allows the function to create a function when it is called. In either case, the nested lambda code can obtain the variable x in the upper lambda function. This works, but this code is quite puzzling. For readability, it is generally best to avoid nested lambdas.





This article is from the "Professor Brother" blog, declined to reprint!

Detailed explanation of lambda anonymous functions in Python 3

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.