Lambda (anonymous function) in Python

Lambda is a frequently used keyword in the Python programming language. Summarized " one syntax, three features, four usages, and one argument " about lambda in Python . – The article is reproduced from " Xiao Ge shelwin ", for personal study only.

A grammar

In Python, the syntax of lambda is unique . Its form is as follows:

lambda argument_list: expression

Among them, lambda is a keyword reserved by Python, and argument_list and expression are customized by the user. The specific introduction is as follows.
1. The argument_list here is the parameter list , and its structure is the same as the parameter list of the function in Python . Specifically, argument_list can have many forms. E.g:

  • a, b
  • a=1, b=2
  • *args
  • ** kwargs
  • a, b=1, *args
  • air

2. The expression here is an expression about parameters. The parameters appearing in the expression need to be defined in argument_list , and the expression can only be a single line. The following are all legal expressions:

  • 1
  • None
  • a + b
  • sum(a)
  • 1 if a >10 else 0

3. The lambda argument_list: expression here represents a function. This function is called a lambda function.

Three characteristics

The lambda function has the following characteristics:
1. The lambda function is anonymous : the so-called anonymous function, in layman's terms, is a function without a name. The lambda function has no name.
2. The lambda function has input and output : the input is the value passed into the argument_list of the parameter list, and the output is the value calculated according to the expression expression.
3. The general function of the lambda function is simple : a single-line expression determines that the lambda function cannot complete complex logic and can only complete very simple functions. Because its realized function is clear at a glance, it doesn't even need a special name to explain it.

Here are some examples of lambda functions:

  • lambda x, y: x y; function input is x and y, output is their product x y
  • lambda: None; the function has no input parameters, and the output is None
  • lambda *args: sum(args); The input is any number of parameters, and the output is their sum (the implicit requirement is that the input parameters must be able to perform addition operations)
  • lambda **kwargs: 1; the input is any key-value pair parameter, the output is 1

Four usages

Since the lambda syntax is fixed , there is essentially only one usage, that is, to define a lambda function . In practice, according to the different application scenarios of this lambda function, the usage of the lambda function can be extended to the following:

1. Assign the lambda function to a variable, and call the lambda function indirectly through this variable .

For example, the execution statement add=lambda x, y: x+y defines the addition function lambda x, y: x+y and assigns it to the variable add, so that the variable add becomes a function with addition function. For example, if add(1,2) is executed, the output is 3.

2. Assign the lambda function to other functions, thereby replacing other functions with the lambda function .

For example, in order to Mock the function sleep in the standard library time, we can call: time.sleep=lambda x:None when the program is initialized. In this way, calling the sleep function of the time library in the subsequent code will not perform the original function. For example, when time.sleep(3) is executed, the program will not sleep for 3 seconds, but will do nothing.

3. Use the lambda function as the return value of other functions and return it to the caller .

The return value of a function can also be a function. For example, return lambda x, y: x+y returns an addition function. At this time, the lambda function is actually a function defined inside a certain function, which is called a nested function, or an inner function. Correspondingly, a function containing nested functions is called an external function. Internal functions can access local variables of external functions. This feature is the basis of Closure programming, and we will not expand it here.

4. Pass the lambda function as a parameter to other functions .

Some built-in Python functions accept functions as parameters. Typical such built-in functions have these.

  • filter function. At this time, the lambda function is used to specify the conditions for filtering the list elements. For example, filter(lambda x: x% 3 == 0,[1, 2, 3]) specifies to filter out the elements in the list [1,2,3] that are divisible by 3, and the result is [3].
  • sorted function. At this time, the lambda function is used to specify the criteria for sorting all elements in the list. For example, sorted([1, 2, 3, 4, 5, 6,7, 8, 9], key=lambda x: abs(5-x)) will list [1, 2, 3, 4, 5, 6, 7,8,9] is sorted according to the distance between the elements and 5 from smallest to largest, and the result is [5, 4, 6, 3, 7, 2, 8, 1, 9].
  • map function. At this time, the lambda function is used to specify the common operation of each element in the list. For example, map(lambda x: x+1, [1, 2,3]) adds 1 to the elements in the list [1, 2, 3], and the result is [2, 3, 4].
  • reduce function. At this time, the lambda function is used to specify the combination of two adjacent elements in the list. For example, reduce(lambda a, b:'{},{}'.format(a, b), [1, 2, 3, 4, 5, 6, 7, 8, 9]) will list [1, 2, The elements in 3, 4, 5,6,7, 8, 9] are combined sequentially from left to right in the form of comma-separated characters, and the result is '1, 2, 3, 4, 5, 6, 7, 8, 9'.

In addition, some Python library functions also receive functions as parameters , such as the spawn function of gevent. At this time, the lambda function can also be passed in as a parameter.

A controversy

In fact, there is controversy about lambda in the Python community . Python programmers are inconsistent on whether to use lambda or not.

  • Supporters believe that the code written with lambda is more compact and more "pythonic".
  • The opponent believes that the functions that lambda functions can support are very limited, and they do not support multi-branch programs if...elif...else... and exception handlers try...except... In addition, the function of lambda function is hidden. For people who are not writing the code, understanding the lambda code requires a certain cost of understanding. They believe that using for loops, etc. instead of lambda is a more straightforward coding style.

The dispute over lambda is inconclusive. In practice, whether to use lambda programming depends on the programmer's personal preference.
The above is the " one syntax, three features, four usages, and one argument " about lambda in Python that we have summarized .

Guess you like

Origin blog.csdn.net/weixin_52385863/article/details/113175499