Python Lambda Brief Introduction

Source: Internet
Author: User

Tag: set return int [1] Cannot assign value expression Test Direct

Python Lambda

In Python, if you want to create a function using the keyword DEF, and if you want to create an anonymous function, you need to use lambda.

What is the difference between a function created by lambda and a function created by def?

  1. Def creates a function that has a name, and Lambda has no
  2. Lambda creates an object of a function, but does not give the object an identifier, and Def assigns the function object to a variable
  3. DEF is a statement, and Lambda is just an expression

    y = lambda x:print (x)
    Y (10) # 10

For example, an expression is created with lambda, and X is equivalent to a formal parameter, and the code as a whole is very simple and efficient.

Typically, a lambda can be directly a member of a list or dictionary, as follows:

So the same operation, in the list, can only use lambda, there is no way to use def substitution, because DEF is a statement, in the list can only be an expression. A lambda expression can have only one expression after ":", usually the return statement can be returned to be placed behind a lambda, and cannot be returned after the same cannot be placed. Therefore, it is best not to put a statement such as if or for in the back of a lambda expression, and lambda is best used only to define simple functions.

Python Lambda Brief Introduction

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.