When should Python use the Lambda function

  • 2021-07-06 11:32:25
  • OfStack

There are two ways to define functions in Python, one is defined by def in the conventional way, and the function should be named, and the other is defined by lambda, which does not need to specify a name, and is called Lambda function.

Lambda function is also called anonymous function, anonymous function is a function without a name, and a function without a name is OK? Of course you can. Some functions don't have to be named if they are temporary and the business logic is simple.

Like the extras in movies, they often have few scenes, but at most they set off the leading role and run a walk-on. Do they need names? No, because they only appear temporarily, they may not need it next time, so there is no need to bother to give each of them a number and a name. After all, it is very difficult to choose an elegant name.

Let's look at a simple lambda function first


>>> lambda x, y : x+y
<function <lambda> at 0x102bc1c80>

x and y are two parameters of the function, and the expression after the colon is the return value of the function. You can see that this function is seeking the sum of two variables, but as a function, how to use it without a name? Let's bind this anonymous function with a name for the time being, which makes it possible for us to call anonymous functions


>>> add = lambda x, y : x+y
>>> add
<function <lambda> at 0x102bc2140>
>>> add(1,2)
3

It is equivalent to a regular function


>>> def add2(x, y):
... return x+y
...
>>> add2
<function add2 at 0x102bc1c80>
>>> add2(1,2)
3

If you define an anonymous function and bind it with a name, it is a bit gilding the lily, usually using lambda function directly. So where is the correct use scenario of lamdba function?

1. Functional programming

Although Python is not a purely functional programming language, it provides many characteristics of functional programming. Functions such as map, reduce, filter and sorted all support functions as parameters, and lambda functions can be applied to functional programming.

Please look at the question: 1 integer list, which is required to be arranged in ascending order according to the absolute value of the elements in the list. What would you do? Think for 1 minute and look down


>>> list1 = [3,5,-4,-1,0,-2,-6]
>>> sorted(list1, key=lambda x: abs(x))
[0, -1, -2, 3, -4, 5, -6]

The sorting function sorted supports receiving 1 function as a parameter, which is the sorting basis of sorted. Here, the absolute value of the list elements is sorted. Of course, I can also use ordinary functions to achieve it:


>>> def foo(x):
... return abs(x)
...
>>> sorted(list1, key=foo)
[0, -1, -2, 3, -4, 5, -6]

It's just that the code doesn't look like Pythonic enough in this way.

2. Closures

Closure itself is an obscure concept, which can be introduced in a separate article, but here we can simply and roughly understand that closure is a function defined inside a function, and closure makes variables accessible even if they are out of the scope of the function.

Let's look at an example of using lambda function as closure.


>>> def my_add(n):
... return lambda x:x+n
...
>>> add_3 = my_add(3)
>>> add_3(7)
10

The lambda function here is a closure. In the global scope, add_3 (7) can execute normally and return a value of 10. The reason why it returns 10 is that in the local scope of my_add, the value of the variable n can be accessed in the global scope because of the closure.

Closures can also be implemented by replacing them with regular functions, but this way is slightly wordy.


>>> def my_add(n):
... def wrapper(x):
... return x+n
... return wrapper
...
>>> add_5 = my_add(5)
>>> add_5(2)
7

So is the lambda function clearer than the regular function in any case? Look at this example:


f = lambda x: [[y for j, y in enumerate(set(x)) if (i >> j) & 1] for i in range(2**len(set(x)))]

This is an lambda function that returns all subsets of a set. Do you understand? It's hard for me to see it

There is such a sentence in zen of python as Explicit is better than implicit (clear is better than obscure). Remember, if using lambda functions doesn't make your code clearer, you should consider defining functions in a conventional way.


Related articles: