Python Basic Learning Lambda

Source: Internet
Author: User

Lambda expression

anonymous functions

The-LAMDBA function is a minimal function that quickly defines a single line, borrowed from Lisp, and can be used wherever a function is needed.

Example:

Function:

>>> def fun (x, y): ... return x*y >>> fun (23,2) Lambda

Lambda X,y:x*y

#lambda function, x first argument, y second argument, x*y operation type, and if the object returned by the function is used, an accepted variable is required >>> A=lambda x,y:x*y>>> A (2,3) 6

Advantage:

When you write some execution scripts using Python, lambda can eliminate the process of defining a function and make the code more streamlined.

For abstractions, functions that do not need to be reused, it is difficult to define names, and the use of lambda does not need to consider name naming;

Using lambda makes the code easier to understand;

Lambda Basics

In a lambda statement, the colon is preceded by a parameter, can be multiple, separated by commas, and the right side of the colon is the return value.

The lambda statement is actually built as a function object;;

>>> Lambda x,y:x*y<function <lambda> at 0x7f9bed0d3578>>>> A=lambda x,y:x*y>>> A<function <lambda> at 0x7f9bed0e58c0>>>> A (2,2) 4

Lambda Application Example:

Reduce is a successive operation of each item in the list, the accepted parameter is 2, and the last returned is a result

Product >>> L=range (1,6) >>> l[1, 2, 3, 4, 5]>>> def f (x, y): ... return x*y ... >>> reduce  (f,l) #将函数f, for L sequence 120 conversion >>> F=lambda x,y:x*y>>> reduce (f,l) 120>>> reduce (lambda x,y:x*y,l) #l列表120 >>>


This article from "thinking More than technology" blog, declined reprint!

Python Basic Learning lambda

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.