search
HomeBackend DevelopmentPython TutorialIntroduction to the usage of lambda function in python (with examples)

This article brings you an introduction to the usage of the lambda function in Python (with examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Anonymous function lambda: refers to a type of function or subroutine that does not need to define an identifier (function name).
The lambda function can receive any number of parameters (including optional parameters) and return the value of a single expression.

Syntax:

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

Before the colon are parameters, there can be multiple, separated by commas, and the one on the right side of the colon is an expression (can only be one). In fact, the return value of lambda is the address of a function, which is the function object.

Example:

1. Assign the lambda function to a variable, and call the lambda function indirectly through this variable.

def sum(x,y):
    return x+y
print(sum(1,2))

Use lambda function:

sum = lambda x,y : x+y
print(sum(1,2))

2. Pass the lambda function as a parameter to other functions. Some Python built-in functions accept functions as parameters.

def odd(x):
    return x%2
temp = range(10)
show = filter(odd,temp)
print(list(show))   #[1, 3, 5, 7, 9]

Use lambda function:

print(list(filter(lambda x: x%2,range(10))))    #[1, 3, 5, 7, 9]

At this time, the lambda function is used to specify the conditions for filtering list elements.

Another example:

map(lambda x: x+1, [1, 2,3])    #[2, 3, 4]

At this time, the lambda function is used to specify a common operation for each element in the list.

In addition: sorted(), map()

3. Return the lambda function to the caller as the return value of other functions.

The return value of a function can also be a function. For example return lambda x, y: x yReturn an addition function. At this time, the lambda function is actually a function defined inside a certain function, called a nested function, or internal function. Correspondingly, functions containing nested functions are called external functions. Inner functions can access local variables of outer functions. This feature is the basis of closure programming.

4. Assign the lambda function to other functions, thereby replacing other functions with the lambda function.

For example, in order to mask (Mock) the function sleep in the standard library time, we can call: time.sleep=lambda x:None during program initialization. In this way, calling the sleep function of the time library in subsequent code will not perform the original function. For example, when executing time.sleep(3), the program will not sleep for 3 seconds, but will do nothing

5. Reduce the if...else statement It is a single conditional expression. The syntax of

is: expression1 if A else expression2

If A is True, the result of the conditional expression is expression1, otherwise it is expression2

def s(x):
    if x==1:
        return "yes"
    else:
        return "no"
print(s(0))
print(s(1))

Using lambda function:

s=lambda x:"yes" if x==1 else "no"
print(s(0))
print(s(1))

[Related recommendations: python video tutorial]

The above is the detailed content of Introduction to the usage of lambda function in python (with examples). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
Python: A Deep Dive into Compilation and InterpretationPython: A Deep Dive into Compilation and InterpretationMay 12, 2025 am 12:14 AM

Pythonusesahybridmodelofcompilationandinterpretation:1)ThePythoninterpretercompilessourcecodeintoplatform-independentbytecode.2)ThePythonVirtualMachine(PVM)thenexecutesthisbytecode,balancingeaseofusewithperformance.

Is Python an interpreted or a compiled language, and why does it matter?Is Python an interpreted or a compiled language, and why does it matter?May 12, 2025 am 12:09 AM

Pythonisbothinterpretedandcompiled.1)It'scompiledtobytecodeforportabilityacrossplatforms.2)Thebytecodeistheninterpreted,allowingfordynamictypingandrapiddevelopment,thoughitmaybeslowerthanfullycompiledlanguages.

For Loop vs While Loop in Python: Key Differences ExplainedFor Loop vs While Loop in Python: Key Differences ExplainedMay 12, 2025 am 12:08 AM

Forloopsareidealwhenyouknowthenumberofiterationsinadvance,whilewhileloopsarebetterforsituationswhereyouneedtoloopuntilaconditionismet.Forloopsaremoreefficientandreadable,suitableforiteratingoversequences,whereaswhileloopsoffermorecontrolandareusefulf

For and While loops: a practical guideFor and While loops: a practical guideMay 12, 2025 am 12:07 AM

Forloopsareusedwhenthenumberofiterationsisknowninadvance,whilewhileloopsareusedwhentheiterationsdependonacondition.1)Forloopsareidealforiteratingoversequenceslikelistsorarrays.2)Whileloopsaresuitableforscenarioswheretheloopcontinuesuntilaspecificcond

Python: Is it Truly Interpreted? Debunking the MythsPython: Is it Truly Interpreted? Debunking the MythsMay 12, 2025 am 12:05 AM

Pythonisnotpurelyinterpreted;itusesahybridapproachofbytecodecompilationandruntimeinterpretation.1)Pythoncompilessourcecodeintobytecode,whichisthenexecutedbythePythonVirtualMachine(PVM).2)Thisprocessallowsforrapiddevelopmentbutcanimpactperformance,req

Python concatenate lists with same elementPython concatenate lists with same elementMay 11, 2025 am 12:08 AM

ToconcatenatelistsinPythonwiththesameelements,use:1)the operatortokeepduplicates,2)asettoremoveduplicates,or3)listcomprehensionforcontroloverduplicates,eachmethodhasdifferentperformanceandorderimplications.

Interpreted vs Compiled Languages: Python's PlaceInterpreted vs Compiled Languages: Python's PlaceMay 11, 2025 am 12:07 AM

Pythonisaninterpretedlanguage,offeringeaseofuseandflexibilitybutfacingperformancelimitationsincriticalapplications.1)InterpretedlanguageslikePythonexecuteline-by-line,allowingimmediatefeedbackandrapidprototyping.2)CompiledlanguageslikeC/C transformt

For and While loops: when do you use each in python?For and While loops: when do you use each in python?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools