Home  >  Article  >  Backend Development  >  What are anonymous functions in python? Grammar and example analysis

What are anonymous functions in python? Grammar and example analysis

乌拉乌拉~
乌拉乌拉~Original
2018-08-15 13:51:542277browse

In today’s article, we will learn about the python anonymous function in python functions. Many people don’t understand what anonymous function means. Today’s article will explain it. Friends, let’s understand what an anonymous function is. Without further ado, let’s start learning about anonymous functions.

Anonymous functions:

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.

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 be able to write only one line, it is not equivalent to the inline function of C or C. The purpose of the latter is to call a small function without occupying stack memory and thereby increase the operating efficiency

Its syntax is as follows:

The syntax of lambda function only contains one statement, as shown in the figure below:

lambda [arg1 [,arg2,.....argn]]:expression

The example is as follows:

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

The above example Output result:

相加后的值为 :  30
相加后的值为 :  40

The above is what I want to explain today, the syntax of anonymous functions and an example. Although there are examples, hands-on practice is the best way to verify what you have learned. Finally, I hope this article can bring some help to you who are learning python.

For more related knowledge, please visit the Python tutorial column on the php Chinese website.

The above is the detailed content of What are anonymous functions in python? Grammar and example analysis. For more information, please follow other related articles on the PHP Chinese website!

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