SoFunction
Updated on 2024-12-20

A brief introduction to Python's lambda anonymous functions

A lambda function is also called an anonymous function, i.e., the function does not have a specific name. Let's start with the simplest example:

Copy Code The code is as follows.

def f(x):
return x**2
print f(4)

In Python, if you use lambda, it is written like this
Copy Code The code is as follows.

g = lambda x : x**2
print g(4)

lambda expressions have corresponding implementations in many programming languages. For example, C#:

Copy Code The code is as follows.

var g = x => x**2
(g(4))

So what is the use of lambda expressions? Many people have questioned the fact that lambda, compared to a normal function, just omits the function name, and at the same time such an anonymous function, cannot be shared to be called elsewhere. In fact, it is true that lambda in Python such a dynamic language really does not play any amazing role, because there are a lot of other ways to replace lambda. at the same time, the use of lambda writing sometimes does not seem so pythonic. even some people proposed that the subsequent version of Python to eliminate lambda.

In retrospect, is there really no use for lambda in Python? Actually, no, at least the points I can think of, mainly:

1. When writing some execution scripts in Python, using lambda can eliminate the process of defining functions and make the code more streamlined.

2. For some abstract functions that will not be reused elsewhere, it is sometimes a challenge to name the function, but with lambda you don't need to consider the naming issue.

3. Using lambda makes the code easier to understand at some point.

Lambda Basics
In a lambda statement, before the colon are the parameters, which can be more than one, separated by commas, and the return value to the right of the colon. what the lambda statement builds is actually a function object, witness:

Copy Code The code is as follows.

g = lambda x : x**2
print g
<function <lambda> at 0x00AFAAF0>

Starting with C# 3.0, lambda expressions are also available, eliminating the need to write them using delegates.The lambda expression keyword in C# is =>, see an example below:
Copy Code The code is as follows.

var array = new int[] {2, 3, 5, 7, 9};
var result = (n => n > 3); // [5, 6, 9]


C# uses extension methods to give array objects handy methods like Where, Sum, etc. Python also has a few well-defined global functions that are easy to use, namely filter, map, reduce.
Copy Code The code is as follows.

>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
>>>
>>> print filter(lambda x: x % 3 == 0, foo)
[18, 9, 24, 12, 27]
>>>
>>> print map(lambda x: x * 2 + 10, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]
>>>
>>> print reduce(lambda x, y: x + y, foo)
139

Non-lambda?
The map in the above example works in the same way as C#'s Where extension method, which is very simple and convenient. But does Python have to use lambda to achieve this level of simplicity? In terms of object traversal, Python's for...in...if syntax is already very powerful and outperforms lambda in terms of readability; for example, the map example above could be written as:

Copy Code The code is as follows.

print [x * 2 + 10 for x in foo]

Very concise and easy to understand. filter example can be written as:
Copy Code The code is as follows.

print [x for x in foo if x % 3 == 0]

Again it is easier to understand than the lambda approach.

So, when to use lambda and when not to use it needs to be analyzed on a case-by-case basis, as long as the intention expressed is clear. In general, I don't choose lambda if for..in..if will do the job.

lambda broken?
In teaching math, lambda is often used, for example, one guy had this problem. He wanted to create an array of functions fs=[f0,... ,f9] where fi(n)=i+n. So then, such a lambda function was defined:

Copy Code The code is as follows.

fs = [(lambda n: i + n) for i in range(10)]

But, strangely enough.
Copy Code The code is as follows.

>>> fs[3](4)
13
>>> fs[4](4)
13
>>> fs[5](4)
13

The results didn't live up to the dude's expectations, as expected they should have:
Copy Code The code is as follows.

>>> fs[3](4)
7
>>> fs[4](4)
8
>>> fs[5](4)
9

The problem is actually with the variable i. The code above is replaced with a simple reduced version that doesn't use lambda:
Copy Code The code is as follows.

i = 1
def fs(n):
return n + i
print fs(1) # 2
i = 2
print fs(1) # 3

As you can see, the reason the above doesn't meet expectations is that the i in the lambda is using a global variable outside the anonymous function. Modify it:
Copy Code The code is as follows.

fs = [(lambda n, i=i : i + n) for i in range(10)]
>>> fs[3](4)
7
>>> fs[4](4)
8
>>> fs[5](4)
9