Python LAMBDA expression

Source: Internet
Author: User

Anonymous Functions
    • A lambda function is a minimal function that quickly defines a single line, and can be used wherever a function is needed
      As an example:
>>> def f(x,y):...     return x*y...>>> f(2,3)6>>> g = lambda x,y:x*y>>> g(2,3)6>>> g<function0x103e12c08>
    1. When using Python to write some execution scripts, using lambda eliminates the process of defining a function, making 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 your code easier to understand at some point.
    4. In a lambda statement, the colon is preceded by a parameter, which can have multiple, comma-separated. After the colon is the return value. A lambda statement is actually built as a function object.
Recursive
5*4*3*2*1120>>> def f(n):...     if0:...         return n*f(n-1)...     if0:...         return1...>>> f(5)120
    • But recursion is not so well understood, so we're leading to reduce
Reduce

You need to define a function to help reduce

>>> l = range(1,6)>>> l[12345]>>> def f(x,y):...     return x*y...>>> reduce(f,l)120

Here we find that the function of defining f is not necessary and can be converted into lambda instead.

>>> reduce(lambda x,y:x*y, l)120

This avoids meaningless function definitions.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Python Lambda expression

Related Article

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.