A summary of the "Three Python learning notes" lambda expression usage

Source: Internet
Author: User
Tags function definition

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.

# ###################### Common function ###################### # defining functions (normal way) def func (ARG):     return arg + 1  #  execution function result = func (123)

However, you can use a lambda expression to achieve the same effect by explicitly assigning the result to a variable name, which can then be called by the variable name.

# ###################### Lambda ######################  # Defining a function (lambda expression) Lambda arg:arg + 1  #  execution function result = MY_LAMBDA (123)

Here F is assigned to a function object created by a lambda expression. This is the task that def accomplishes, except that the Def assignment is automatic.

The 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 wants to follow the same action on the lookup rule as the code inside the def. A local scope introduced by a lambda expression is more like a nested DEF statement, and will automatically find the variable name from the upper function, the module, and the built-in scope (through the LEGB rule).

def Knights ():     ... " Sir " ...     = (lambda' + x)     ... return action ... >>> act = Knight ()>>> Act ('Robin')'  Sir Robin'

In Python 2, the value of the variable name title is usually modified to pass in by the value of the default parameter.

Why use Lambda

In general, lambda acts as a function sketch, allowing the definition of a function to be embedded within the code used. They are completely optional (you can always use DEF to replace them), but you only need to embed small pieces of executable code in case they bring a more concise code structure.

For example, we will see a callback handler later, which often writes a single-line lambda expression in the parameter list of a registered call (registration. T), rather than using a def in the other part of the file to define it, and then references that variable name.

Lambda is usually used to write a jump table, or a list or dictionary of behaviors, to perform the corresponding action as needed. The following snippet shows the code.

L = [lambda x:x**2,     Lambda x:x**3,     Lambda x:x**4    for in L:    print(f (2))            #  Prints 4, 8,     Print (L[0] (3))             # Prints 9

Lambda expressions are most useful as a shorthand for def when it is necessary to write a small piece of executable code into a place where the DEF statement is syntactically impossible to write into. For example, this code fragment can create a list of three functions by embedding a lambda expression in a list constant. A def does not work in a list constant, because it is a statement, not an expression. The equivalent DEF code may need to have temporary function names and function definitions outside of the environment that you want to use.

def return x**2defreturn x**3defreturn x**4=for   in L:    print(f (2))            #  Prints 4, 8,      Print(L[0] (3))             #  Prints 9

In fact, we can use a dictionary or other data structure in Python to build more kinds of behavior tables to do the same thing. Here is another example given in the interactive hint mode:

' got '>>> {'already': (lambda: 2 + 2),...   ' got ':     (lambda: 2 * 4),...   '  One ':     (lambda: 2 * * 6)}[key] ()8

Here, when Python is familiar with this dictionary, 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 allow the removed function to be called. This code can make the dictionary a more versatile branch tool than the extended usage of the IF statement you showed earlier.

If you do not do this with lambda, you will need to use the DEF statements that have occurred elsewhere in the three files, that is, you need to define these functions somewhere outside of the dictionary that these functions will use.

>>>defF1 ():return2 + 2...>>>defF2 ():return2 * 4...>>>defF3 ():return2 * * 6...>>> key =' One'>>> {'already': F1,'got': F2,' One': F3} [Key] ()64

Similarly, the same functionality is achieved, but def may appear anywhere in the file, even after they have very little code. The code, like the lambda just now, provides a particularly useful function that can occur in a single case: if three of these functions are not used elsewhere, it makes sense to embed them as lambda in the dictionary. Not only that, the DEF format requires that you create variable names for these small functions, which might conflict with other variable names in the file (or it may not, but is always possible).

How to (don't) make Python code difficult to understand

Since the body of a lambda must be an expression (rather than some statements), this shows that only limited logic can be encapsulated in a lambda. If you know what you're doing, you can write enough statements in Python as an expression-based equivalent.

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

if A:    belse:    c

Can be modeled by the following generalized equivalent expressions:

if Else  andor c)

Because such expressions can be placed in a lambda, they are able to implement the selection logic in a lambda function.

>>> lower = (LambdaX, y:xifX < yElsey)>>> Lower ('BB','AA')'AA'>>> Lower ('AA','BB')'AA'

In addition, if you need to perform loops in a lambda function, you can embed a tool such as a map call or a list-resolution expression.

>>>ImportSYS>>> ShowAll =Lambdax:list (Map (sys.stdout.write, x))>>> t = showall (['spam\n','toast\n','eggs\n']) Spamtoasteggs>>> ShowAll =Lambdax: [Sys.stdout.write (line) forLineinchX#List Parsing>>> t = showall (['spam\n','toast\n','eggs\n']) Spamtoasteggs

These techniques must be used only in case of last resort. Accidentally, they lead to unreadable (and obscure) Python code. Generally speaking, brevity is better than complexity, clarity is better than obscurity, and a complete statement is better than a mysterious expression. That's 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 side, you will also find that the use of humidity is useful in these techniques.

Nesting Lambda and scopes

Lambda is the largest beneficiary of nested function scoping lookups (E in the LEGB principle). For example, in the following example, Lambda appears in Def (a typical case), and when the marketplace 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 +>>> act = Action ()>>> Act<function action. <locals>.<Lambda> at 0x0000014ef59f4c80>>>> Act (2)101

The previous discussion about nested function scopes does not indicate that lambda can also get the variable names in any upper lambda. This is a bit cryptic, but imagine if we were to replace the high-end def with a lambda in the last example.

>>> action = (lambda x: (lambda y:x + y))>>> act = action (>&G) T;> Act (3)102>>> ((lambda x: (lambda y:x + y)) (4)103

The lambda structure nested here allows the function to create a function at the time of invocation. In either case, the nested lambda code is able to get the variable x in the upper-level lambda function. This can work, but the code is quite confusing. In terms of readability, it is generally preferable to avoid using nested lambda.

A summary of the "Three Python learning notes" lambda expression usage

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.