Usage of Python Lambda

Source: Internet
Author: User

Turn from: Another self

Use of the anonymous function lambda

In Python, a lambda function is also called an anonymous function, and a function without a specific name, which allows you to quickly define a single-line function, similar to a C-language macro, that can be used wherever a function is needed. This is distinguished from the function defined by def.
The difference between Lambda and def:
1) def creates a method that has a name, and Lambda does not.
2) lambda Returns a function object, but the object is not assigned an identifier, and Def assigns the function object to a variable (the name of the letter).
3) Lambda is just an expression, and DEF is a statement.
4) After the lambda expression ":", there can be only one expression, and the Def may have multiple.
5) Statements such as if or for or print cannot be used in lambda, Def can.
6) Lambda is typically used to define simple functions, and DEF can define complex functions.
6) Lambda functions cannot be shared to other program calls, Def can.
Lambda syntax format:
Lambda variable: the statement to execute

1 Lambda [Arg1 [, Agr2,..... argn]: expression

Such as:

1 1, single parameter:2Lambda x:x * * 23print g (3)4 9  5 2, multiple parameters:6Lambda x, Y, Z: (x + y) * * z7print g ( , 2)8 9

A lambda expression returns a function object that will soon be discarded if no variable accepts the return value. It is also because Lambda is just an expression, so it can be used directly as a member of List and Dict. Such as:

1 >>> list_a = [lambdaLambda b:b**3]2 >>> list_a[0 ]3 <function <lambda> at 0x0259b8b0>4 >>> g = List_a[0] C10>5 >>> g (2)6 8

There is no way to replace the DEF statement, and the statement cannot be nested inside. In a lambda expression, a colon is preceded by a parameter, can have multiple, separated by commas, and a return value to the right of the colon.
Lambda is not a specific use, depending on the situation, sometimes using lambda can simplify the code.

Usage of Python Lambda

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.