A brief introduction to lambda anonymous functions in Python

Source: Internet
Author: User
A brief introduction to lambda anonymous functions in Python. For more information, see lambda functions. Let's take a look at the simplest example:

The code is as follows:


Def f (x ):
Return x ** 2
Print f (4)


If lambda is used in Python, it is written as follows:

The code is as follows:


G = lambda x: x ** 2
Print g (4)

Lambda expressions are implemented in many programming languages. For example, C #:

The code is as follows:


Var g = x => x ** 2
Console. WriteLine (g (4 ))


So what is the use of lambda expressions? Many people have raised questions. lambda saves the name of a function compared to a common function, and such an anonymous function cannot be called elsewhere. Actually, it is true that lambda does not play an amazing role in a dynamic language like Python, because there are many other ways to replace lambda. At the same time, lambda statements sometimes seem less pythonic. Some even suggested that lambda should be canceled in later Python versions.

Looking back, is lambda really useless in Python? Actually not. at least I can think of the following points:

1. when using Python to write some execution scripts, using lambda can save the process of defining functions and simplify the code.

2. for some abstract functions that will not be reused elsewhere, it is also difficult to give them a name. you do not need to consider naming when using lambda.

3. use lambda to make the code easier to understand in some cases.

Lambda basics
In a lambda statement, there are multiple parameters before the colon, which can be separated by commas (,). return values on the right of the colon. Lambda statements are actually built as a function object. let's see:

The code is as follows:


G = lambda x: x ** 2
Print g
At 0x00AFAAF0>


C #3.0 starts with lambda expressions, saving you the trouble of using delegate. In C #, the lambda expression keyword is =>. let's look at the following example:

The code is as follows:


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



C # Using the extension method makes the array object have a convenient method like Where and Sum. In Python, there are also several defined global functions that are easy to use. They are filter, map, and reduce.

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

Not lambda?
The role of map in the above example is the same as the Where extension method in C #, which is very simple and convenient. But does Python require lambda to be concise? In terms of object traversal processing, Python's for... in... if syntax is already very powerful, and it is better than lambda in terms of readability. For example, the preceding map example can be written as follows:

The code is as follows:


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


Very simple and easy to understand. The filter example can be written as follows:

The code is as follows:


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


It is also easier to understand than lambda.

Therefore, when lambda is used, when it is not used, and specific analysis is required, as long as the intent is clearly expressed. In general, if for... in... if can do it, I will not select lambda.

Lambda broken?
Lambda is often used in mathematics teaching. for example, a dude encountered such a problem. He wants to create a function array fs = [f0,..., f9] where fi (n) = I + n. Then, he defines a lambda function:

The code is as follows:


Fs = [(lambda n: I + n) for I in range (10)]


But the strange thing is,

The code is as follows:


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


The result did not meet the expectation of this dude. the expected result should be:

The code is as follows:


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


The problem lies in variable I. The above code changes to a simple version that does not use lambda:

The code is as follows:


I = 1
Def fs (n ):
Return n + I
Print fs (1) #2
I = 2
Print fs (1) #3


It can be seen that the above is not as expected because I in lambda uses global variables outside of anonymous functions. Modify:

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.