Home  >  Article  >  Backend Development  >  Anonymous function in Python - lambda

Anonymous function in Python - lambda

高洛峰
高洛峰Original
2016-10-19 13:31:271290browse

Brief description

In addition to the def statement, Python also provides an expression form that generates function objects. This expression creates a function that can be called later, but it returns a function instead of assigning the function to a variable name.

lambda expression

The general form of lambda is the keyword lambda, followed by one or more parameters, followed by a colon, followed by an expression: lambda argument1 argument2 ... :expression using arguments

lambda is an expression, not a statement.

As an expression, lambda returns a value that can optionally be assigned to a variable name. In contrast, a def statement always assigns a new function to a variable name at the beginning, rather than returning the function as a result.

The lambda body is a single expression, not a block of code.

Default parameters can also be used in lambda parameters, just like they are used in def.

>>>x = (lambda a = "www.", b = "pythontab", c = ".com": a + b +c)

>>>x("bbs")

'bbs .pythontab.com'

Why use lambda

1. When using Python to write some execution scripts, using lambda can save the process of defining functions and make the code more streamlined.

2. For some abstract functions that will not be reused elsewhere, sometimes it is difficult to name the function. Using lambda does not require naming issues.

3. Use lambda to make the code easier to understand at certain times.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn