A brief introduction to Python's Lambda anonymous function

Source: Internet
Author: User
A lambda function is also called an anonymous function, that is, the function does not have a specific name. Let's take a look at one of the simplest examples:
Copy CodeThe code is as follows:


def f (x):
Return x**2
Print F (4)


Using lambda in Python, it's written like this
Copy CodeThe code is as follows:


g = Lambda x:x**2
Print g (4)

Lambda expressions have a corresponding implementation in many programming languages. such as C #:
Copy the Code code as follows:


var g = x = X**2
Console.WriteLine (g (4))


So what is the use of lambda expressions? Many people have questioned that lambda, compared to normal functions, eliminates the function name, while such anonymous functions cannot be shared elsewhere. It's true that Lambda does not play a big role in the dynamic language of Python, because there are many other ways to replace Lambda. At the same time, the use of lambda notation is sometimes less pythonic. It is even suggested that after the Python version to cancel the lambda.

Looking back, does the lambda in Python really come into play? In fact not, at least I can think of the point, mainly have:

1. When using Python to write some execution scripts, using lambda eliminates the process of defining a function and makes the code more streamlined.

2. For some abstract functions that are not reused elsewhere, sometimes it is difficult to name a function, and using lambda does not have to consider naming problems.

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

Lambda Basics
In a lambda statement, the colon is preceded by a parameter, which can have multiple, separated by commas, and a return value to the right of the colon. The lambda statement is actually built as a function object, witnessing:
Copy the Code code as follows:


g = Lambda x:x**2
Print g
At 0x00afaaf0>


C#3.0 begins with a lambda expression, eliminating the hassle of using delegate. The lambda expression keyword in C # is => look at one of the following examples:
Copy CodeThe code is as follows:


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



C # uses extension methods to make the array object have a convenient way like where,sum. In Python, there are also several well-defined global functions that are easy to use, they are filter, map, reduce.
Copy CodeThe 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 + ten, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]
>>>
>>> print reduce (lambda x, y:x + y, foo)
139

Not lambda?
The map in the example above has the same function as the where extension method in C #, which is very simple and convenient. But does Python have to use lambda to make this simple? In the object traversal process, in fact Python for. In.. The IF syntax is already strong and is more readable than lambda. For example, the map above can be written as:
Copy the Code code as follows:


print [x * 2 + ten for x in Foo]


It's very concise and easy to understand. The filter example can be written as:
Copy CodeThe code is as follows:


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


It's also easier to understand than a lambda way.

So, when to use lambda, when not to, need specific case specific analysis, as long as the expression of the intention clearly good. In general, if for: In.. If I can do that, I will not choose lambda.

Lambda broken?
In math teaching, lambda is often used, such as having a man who encounters such a problem. He wants to create an array of functions fs=[f0,..., F9] where FI (n) =i+n. Thus, a lambda function is defined:
Copy the Code code as follows:


FS = [(lambda n:i + N) for I in range (10)]


But, oddly enough,
Copy CodeThe code is as follows:


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


The result did not meet the man's expectations, and the expected result would be:
Copy CodeThe code is as follows:


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


The problem is actually on the variable i. The code above is a simple, reduced version that does not use lambda:
Copy CodeThe 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 above is not expected is that I in Lambda uses a global variable outside of the anonymous function. Modify:
Copy CodeThe 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.