Usage of lambda in Python

Source: Internet
Author: User

The lambda function is also called an anonymous function, that is, the function does not have a specific name. Let's take a look at one of the simplest examples:

def f (x):
Return x**2
Print F (4)

Using lambda in Python, it's written like this

g = Lambda x:x**2
Print g (4)

Second, lambda and the normal function, is to omit the function name, while such an anonymous function, and can not be shared in other places called.

It's true that Lambda does not play a big role in the dynamic language of Python, because there are many other ways to replace Lambda.

1. When using Python to write some execution scripts, using lambda eliminates the process of defining a function and makes 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 the code easier to understand at some point.

Lambda Basics

In a lambda statement, the colon is preceded by a parameter, which can have multiple, separated by commas, and a return value to the right of the colon. The lambda statement is actually built as a function object, witnessing:

>>> foo = [2, 18, 9, 22, 17, 24, 8, 12, 27]
>>> Print filter (lambda x:x% 3 = = 0, foo)
[18, 9, 24, 12, 27]
>>> Print Map (Lambda x:x * 2 + ten, foo)
[14, 46, 28, 54, 44, 58, 26, 34, 64]
>>> print reduce (lambda x, y:x + y, foo)
139

In the object traversal process, in fact Python for. In.. The IF syntax is already strong and is more readable than lambda.

Usage of lambda in Python

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.