python anonymous function related summary

  • 2021-10-15 10:56:52
  • OfStack

Directory 01 What is an anonymous function?
02 functional programming
03 What is the performance of lambda?

When writing python, in most scenarios, I am an if else player, because the core logic is almost realized through if else statement. About the anonymous function this block, actually can use the common loop and other methods to achieve, but if you want to become a master of python, anonymous functions must be understood. Because anonymous functions can make your code concise enough.

01 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. The anonymous function format is as follows:

lambda arg1,arg2 ...,argN : expression

Its common format is lambda keyword + comma-separated parameter + colon + expression.

Take a simple example:


---- 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 perform the squared operation of a number x, in which * * stands for the power operation.

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

Of course, we can also define a function to implement the power operation.

One thing that distinguishes lambda from a function is that lambda is an expression, not a function, nor a statement. Therefore, lambda can be used in one special place, such as the following scenario:

We can use the range function to generate an list, as follows:


>>> a=[ range(10)]    
>>> a
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]

If we want to do power operation on these numbers, we can write them directly as follows:


>>> b=[(lambda x: x*x)(x) for x in range(10)]
>>> b
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
---- If you use a function to implement it, you will find an error ---
>>> def fun(x):
...  return x**2
... 
>>> 
>>> c=[fun(range(10))]
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "<stdin>", line 2, in fun
TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'

Of course, you can also use functions and use other methods to implement this process as follows:


>>> def fun2(x):
...  return x**2
... 
>>> c=[]
>>> for i in range(10):
...   c.append(fun2(i))
>>> c
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Compared with the previous lambda function, this method is not so dexterous.

02 functional programming

The so-called functional programming means that every block in the code is immutable and is composed of functions. The functions themselves are independent of each other and do not affect each other. The same input corresponds to the same output. The characteristics of functional programming are closely related to lambda.

Let's look at the following example. If we want to multiply all the elements in an list by 2, we can write it in the following form:


>>> l=[1,2,3,4,5]
>>> def double_num(l):
...  for index in range(0, len(l)):
...    l[index] *= 2
...  return l
... 
>>> double_num(l)
[2, 4, 6, 8, 10]
>>> l
[2, 4, 6, 8, 10]

The above code is not an example of functional programming.

Because the value of L changes every time we enter the list L, if we call the function double_num many times, the result will be different every time.

So if we make it a functional program, we have to write it like this:


>>> l=[1,2,3,4,5]          
>>> def double_num1(l): 
...   new_list=[]
...   for index in l: 
...     new_list.append(index*2)
...   return new_list
... 
>>> double_num1(l)
[2, 4, 6, 8, 10]
>>> l
[1, 2, 3, 4, 5]

In python, several commonly used functions map, filter, reduce are provided to use with lambda1 to realize functional programming (note that these three functions need to be used in python3 environment).

map Function map (function, list)

Note that function here can be an anonymous function or a normal function.

Or the above example of multiplying by 2, if we use map function with lambda to achieve it, it can be written as follows:


>>> l = [1, 2, 3, 4, 5] 
>>> new_list = map(lambda x: x * 2, l)       
>>> for i in new_list:
...  print(i)
... 
2
4
6
8
10

Here, lambda can be replaced by functions, as follows:


>>> l = [1, 2, 3, 4, 5]  
>>> def double_x(x):
...  return x*2
>>> res=map(double_x, l)
>>> for i in res:
...  print(i)
... 
2
4
6
8
10

filter Function filter (function, list)

The filter function is mainly used to judge each element in the iterative object with function, return the object returning true, and discard the object returning false, as follows:


>>> l = [1, 2, 3, 4, 5]  
>>> new_l=filter(lambda x: x%2==0, l)
>>> for i in new_l:
...   print(i)
... 
2
4

reduce Function reduce (function, list)

reduce is mainly used to do some cumulative operations on a list. If we want to calculate the cumulative product of a list, we can use the following methods:


>>> from functools import reduce
>>> l = [1, 2, 3, 4, 5]                  
>>> product = reduce(lambda x,y: x*y, l) 
>>> product
120

03 What is the performance of lambda?

The following is an example to test the time consumption of multiplying a collection element by 2 by lambda, for loop and creating a new list under different schemes:


>>> a=[ range(10)]    
>>> a
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]]
0

As you can see, when using map+lambda, the performance is better. map function is written by c language, run without the python interpreter, and do a lot of internal optimization, so the performance will be better.

The above is the python anonymous function related summary details, more information about python anonymous function please pay attention to other related articles on this site!


Related articles: