A brief introduction to lambda in Python

Source: Internet
Author: User

1. What is lambda?
Func=lambda X:x+1print (func (1)) #2print (func (2)) #3 # above Lambda equals the following function def func (x):    return (x+1)

It can be thought that lambda, as an expression, defines an anonymous function, where code x is the entry parameter and x+1 is the function body. Here Lambda simplifies the writing of function definitions. Code is more concise, but the use of functions is more intuitive and easy to understand.

In Python, there are also several well-defined global functions that are easy to use, filter, map, reduce.

From functools import reduce foo = [2, 9, 8, A, 27]print (list (filter (lambda x:x% 3 = = 0, foo)) #[18, 9  , 2, 27]print (list (map (lambda x:x * +, foo))) #[14, x, I, Si, si, si, si, 64]print (Reduce (lambda x, y:x + y, foo)) #139

  

The role of the map in the example above is very simple and clear. 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: print ([x * 2 + x in Foo]) is very concise and easy to understand.

The filter example can be written as: print ([x for X in foo if x% 3 = = 0]) is also easier to understand than Lambda's way.

A brief introduction to lambda 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.