lambda Expressions in Python

Source: Internet
Author: User

Lambda expressions are a common form of writing for anonymous methods in Python programs, which are very simple to write, but at the expense of readability. Let's look at a brief introduction to lambda.

Grammar

Lambda [Parameter_list]:expression

The return value of a lambda expression is a function, [parameter_list] is a function parameter, and expression is a specific operation. Its corresponding non-anonymous method is written in the following way:

def function ([parameter_list]):    expression

As in the following example:

# Function def func (N):     return n + 1print(func (2))#Lambdalambda x:x+1Print  (f)print(f (2))

The first is the addition of a normal non-anonymous function, and the second is the lambda representation of the anonymous function. The x in the lambda is the parameter of the expression return function, x+1 is the specific function content. Because the lambda expression returns an anonymous function, the print result is:

Of course, lambda expressions also have the following use cases:

#Multi-parameter casePrint("Multi-parameter case") Multi=Lambdax,y,z:x+y+ZPrint(multi ())#working with non-anonymous functionsPrint("working with non-anonymous functions")defNamedfunc (n):return Lambdax:n+xPrint(Namedfunc (2))#will print out function, equivalent to lambda x:2+xPrint(Namedfunc (2) (3))#will print out 5F= Namedfunc (2)Print(f (3))#equivalent to Namedfunc (2) (3)

The results are as follows:

Some small suggestions for lambda expressions in Python programs:

1. For simple logic processing, you can safely use lambda expressions, which is more concise

2. For complex logic processing, avoid using lambda expressions, poor readability, and error-prone (except Daniel)

lambda Expressions in Python

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.