Talk briefly about the lambda expression in python

  • 2020-07-21 08:50:38
  • OfStack

There are many advantages to using lambda that have been discovered recently in coding. Many times the code is cleaner and more pythonic, so here is a brief summary of 1

1. lambda is what

Here's a simple example:


func = lambda x: x*x

def func(x):
 return x*x

The definitions of func and func are exactly the same. The two function definitions are used together with map to square all the elements in list. What would the code look like?


def func(x):
  return x*x
map(func, [i for i in range(10)])
map(lambda x: x*x, [i for i in range(10)])

By contrast, the effect is clear. First of all, the function of func is 10 points simple, and it is likely to be used only once, so here we define a function with simple function and low frequency of use. In this example, using lambda to create anonymous functions does not affect the readability of the code, but it also simplifies the code and reduces unnecessary function calls. In fact, this scenario is very common, we need a simple one-line function, do a simple thing, we don't even care about the name of the function, lambda is a good choice.

2. Use lambda or not

lambda defines an anonymous function that does not increase code execution efficiency. lambda is often used in conjunction with map, reduce, and filter for traversing lists, but the pursuit of lambda for 1 flavor is often disastrous for code readability. python has strict constraints on lambda because it can only consist of one expression. lambda is convenient, but if you overdo it, the logic of the program doesn't seem so clear. After all, everyone understands abstractions differently.

If I have a list generation and only use for, if, in, I won't use lambda

If the function is not simple enough and involves complex logic such as loops, I will define the function to make the code more readable and I will not use lambda at this point

In my opinion, lambda exists to reduce the definition of single-line functions, so it is sufficient to replace the definition of single-line functions.


Related articles: