Eraser, a new series of fun Internet advanced webworms, let’s Be More Pythonic together.

Lambda expressions

5.1 Basic use of lambda expressions

Lambda expressions are also called anonymous functions. They do not have a specific name when defining them. They are commonly used to quickly define single-line functions.

fun = lambda x:x+1
print(fun(1))
Copy the code

If you look at the code above, you can see that a lambda expression defines a line of functions with no function name, followed by the function function, which performs the +1 operation on x. A little formatting:

lambda[Parameter list]: expression# English syntax format
lambda [arg1[,arg2,arg3....argN]]:expression
Copy the code

There are a few considerations in the syntax format:

  1. Lambda expressions must be defined using the lambda keyword;
  2. After the lambda keyword and before the colon is the list of arguments, which can range from 0 to any number of arguments. Multiple arguments are separated by commas, with the return value of the lambda expression to the right of the colon.

The code at the beginning of this article, if you want to rewrite it as a general function, looks like this:

fun = lambda x:x+1
# rewrite the function form as follows:
def fun(x) :return x+1
Copy the code

Of course, if you decide that fun is redundant, anonymous functions should not be redundant, and you could write it like this, but the code becomes less readable.

print((lambda x:x+1) (1))
Copy the code

Lambda expressions are typically used for functions that do not need to be used more than once, and that free up space when the function is done.

5.2 Differences between lambda expressions and def defined functions

First point: one has a function name and one doesn’t

Second point: lambda expressions: after, can only have one expression, multiple will error, that is, the following code will not appear.

# All wrong
lambda x:x+1 x+2
Copy the code

For this reason, many people also refer to lambda expressions as single-expression functions.

Third point: the for statement cannot be used in a lambda. There are places where the if statement and the print statement cannot be used in a lambda expression. This description is inaccurate.

lambda a: 1 if a > 10 else 0
Copy the code

The basic conclusion is that lambda expressions are allowed to contain only one expression, no complex statements, and the result of that expression is the return value of the function.

Fourth point: Lambda expressions cannot be shared with other program calls

Fifth point: Lambda expressions can be used as values of other data types, as shown in the following code.

my_list = [lambda a: a**2.lambda b: b**2]
fun = my_list[0]
print(fun(2))
Copy the code

5.3 Lambda Expression Application Scenarios

In specific coding scenarios, lambda expressions are commonly used as follows:

1. Assign a lambda expression to a variable, and then call the variable.

fun = lambda a: a**2
print(fun(2))
Copy the code

2. Assign lambda expressions to other functions to replace the functions of other functions. This is usually done to mask some functions, such as the built-in sorted function.

sorted = lambda *args:None
x = sorted([3.2.1])
print(x)
Copy the code

In some functions, anonymous functions are acceptable in function Settings, such as the following sort code:

my_list = [(1.2), (3.1), (4.0), (11.4)]
my_list.sort(key=lambda x: x[1])
print(my_list)
Copy the code

The my_list variable calls sort, and the key argument assigns a lambda expression that sorts by the second item of each element in the list.

4. Apply lambda expressions to filter, map, and Reduce higher-order functions.

This technique leads to the conclusion that the return value of a function is also a function, as shown in the following code:

def fun(n) :
    return lambda x:x+n

new_fun = fun(2)
print(new_fun)

      
       .
       
         at 0x00000000028A42F0>
       
      
Copy the code

In the above code, lambda expressions are actually functions defined inside a function, called nested functions, or inner functions. Corresponding functions that contain nested functions are called external functions. Closure programming is based on the ability of internal functions to access local variables of external functions. There will also be a blog post on Closure programming in the second round of Snowball Python.

5.4 Don’t abuse lambda

Lambda expressions have some advantages, but lambdas should not be overused. The latest official Python style guide, PEP8, advises never to write code that:

normalize_case = lambda s: s.casefold()
Copy the code

So if you want to create a function and store it in a variable, use def to define it.

Unnecessary encapsulation We implement a list sort by absolute value.

my_list = [-1.2.0, -3.1.1.2.5]
sorted_list = sorted(my_list, key=lambda n: abs(n))
print(sorted_list)
Copy the code

The above seems to use lambda expressions, but it is forgotten that in Python all functions can be passed as arguments.

my_list = [-1.2.0, -3.1.1.2.5]
sorted_list = sorted(my_list, key=abs)
print(sorted_list)
Copy the code

That is, when we have a function that satisfies the requirement, there is no need to use lambda expressions in addition.

For more, eraser also found a good blog that you can read specifically: Reference address

5.5 Summary of this blog

Lambda expressions do not make the program run more efficiently, only make the code more concise. Lambda expressions exist to reduce the definition of single-line functions.

Blogger ID: Dream eraser, hope you like, comment, favorites.