Python's Lambda Python anonymous function lambda

Python anonymous function lambda

 

 A lambda expression can only have one expression after ":". That is to say, in def, what can be returned by return can also be placed after lambda , and what cannot be returned by return cannot be defined after python  lambda . Therefore, something likeStatements such as if or for or print cannot be used in lambdas , which are generally only used to define simple functions

Although Python is not a functional programming language, it still gives great importance to functional programming. In the next few articles I will document some knowledge of functional programming in Python, among which this article is going to talk about anonymous function lambdas.

Python uses the lambda keyword to create anonymous functions. The so-called anonymous means that a function is no longer defined in a standard form such as the def statement. The purpose of this statement is to bypass the stack allocation of a function when it is called for performance reasons. Its syntax is:

lambda [arg1[, arg2, ... argN]]: expression

Among them, the parameters are optional, if used, the parameters usually appear in the expression.

The following example shows how to use the lambda statement (without parameters).

 

 

Here is another example with parameters.

 

 

Does it look like the code is more concise without losing readability.

 A lambda expression can only have one expression after ":". That is to say, in def, what can be returned by return can also be placed after lambda , and what cannot be returned by return cannot be defined after python  lambda . Therefore, something likeStatements such as if or for or print cannot be used in lambdas , which are generally only used to define simple functions

Although Python is not a functional programming language, it still gives great importance to functional programming. In the next few articles I will document some knowledge of functional programming in Python, among which this article is going to talk about anonymous function lambdas.

Python uses the lambda keyword to create anonymous functions. The so-called anonymous means that a function is no longer defined in a standard form such as the def statement. The purpose of this statement is to bypass the stack allocation of a function when it is called for performance reasons. Its syntax is:

lambda [arg1[, arg2, ... argN]]: expression

Among them, the parameters are optional, if used, the parameters usually appear in the expression.

The following example shows how to use the lambda statement (without parameters).

 

 

Here is another example with parameters.

 

 

Does it look like the code is more concise without losing readability.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325987013&siteId=291194637