Instance Usage of python Anonymous Function

  • 2021-10-15 11:08:00
  • OfStack

In general, lambda is like a function simplifier, which allows the definition of a function to be embedded in the code used. They are completely optional (def can be used to replace them for 1 straight), but embedding only a small amount of executable code can make the code structure more concise, thus greatly simplifying the code complexity and improving the code readability.

1. Advantages

(1) Reduce duplicate codes;

(2) Modular code.

2. Examples


# def Function 
def square(x):
  return x**2
squared = map(square, [1, 2, 3, 4, 5])
 # lambda Function 
squared = map(lambda x: x**2, [1, 2, 3, 4, 5])

Extension of knowledge points:

What is an anonymous function

In python, anonymous functions, as their name implies, are functions without names, which are mainly used in scenarios that are used only once. If we only need to call a simple logic once in our program, we need to define and take the name of the function to write it as a function. Using anonymous functions in this scenario can often make your program simpler.

The anonymous function also has a name, called lambda


---- Calculation 1 Square of the number ---
>>> lambda x: x**2
<function <lambda> at 0x7f6ebe013a28> 
--- Note that this is 1 The address of a function ---
>>> func=lambda x: x**2
>>> func(2)
4
>>> 
>>> func(3)
9

Using lambda, we squared a number x, and in python, * * stands for power operation.

In the above example, x is the parameter, and x**2 after the colon is the expression expression.


Related articles: