How to use python lambda

藏色散人
Release: 2019-08-01 15:35:06
Original
4145 people have browsed it

How to use python lambda

How to use python lambda?

python uses lambda to create anonymous functions.

lambda is just an expression, and the function body is much simpler than def.

The body of lambda is an expression, not a code block. Only limited logic can be encapsulated in lambda expressions.

The lambda function has its own namespace and cannot access parameters outside its own parameter list or in the global namespace.

Although the lambda function seems to only be able to write one line, it is not equivalent to the inline function of C or C. The purpose of the latter is to not occupy the stack memory when calling a small function and thus increase the operating efficiency.

Grammar

The syntax of the lambda function only contains one statement, as follows:

lambda [arg1 [,arg2,.....argn]]:expression
Copy after login

Example (Python 2.0)

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 可写函数说明
sum = lambda arg1, arg2: arg1 + arg2;
 
# 调用sum函数
print "相加后的值为 : ", sum( 10, 20 )
print "相加后的值为 : ", sum( 20, 20 )
Copy after login

Output results of the above examples:

相加后的值为 :  30
相加后的值为 :  40
Copy after login

Related recommendations: "Python Tutorial"

The above is the detailed content of How to use python lambda. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template