Sie sind auf Seite 1von 13

03/12/2015

WhyarePythonlambdasuseful?StackOverflow

signup

login

tour

help

stackoverflowcareers

Signup

StackOverflowisacommunityof4.7millionprogrammers,justlikeyou,helpingeachother.Jointhemitonlytakesaminute:

WhyarePythonlambdasuseful?[closed]
I'mtryingtofigureoutpythonlambdas.Islambdaoneofthose'interesting'languageitemsthatinreallifeshouldbeforgotten?
I'msuretherearesomeedgecaseswhereitmightbeneeded,butgiventheobscurityofit,thepotentialofitbeingredefinedinfuture
releases(myassumptionbasedonthevariousdefinitionsofit)andthereducedcodingclarityshoulditbeavoided?
Thisremindsmeofoverflowing(bufferoverflow)ofCtypespointingtothetopvariableandoverloadingtosettheotherfieldvalues.It
feelslikesortofatechieshowmanshipbutmaintenancecodernightmare.
python lambda

editedyesterday

askedMay20'09at20:40

ajcr
25.3k

meade
7

42

62

6,029

10

21

35

closedastoobroadbymeagar Nov14at16:59
Thereareeithertoomanypossibleanswers,orgoodanswerswouldbetoolongforthisformat.Pleaseadddetailstonarrowtheanswersetortoisolatean
issuethatcanbeansweredinafewparagraphs.
Ifthisquestioncanberewordedtofittherulesinthehelpcenter,pleaseeditthequestion.

90

Well,Idon'tthinkyou'dlikeJavaScriptmuchthen...andgoodLord,stayawayfromHaskell!JALJan
16'10at15:43

153 +1Goodquestionbadassumptions(obscurityoflambda)=)Trynottobejudgmentalofprogramming
techniques.Evaluatethem,andaddthemtoyourmentaltoolkit.Ifyoudon'tlikethem,don'tusethem,
andbepreparedtodiscussthemlogicallywithoutbecomingreligious.KieveliFeb23'10at13:27
23

HaskellRules!Lambdafunctionsgivesyouexpressivityandabstractionpower.JonathanBarberoFeb
23'10at13:31

@JALNottomentionLISP...ApproachingDarknessFishFeb24'14at0:41

26Answers

Areyoutalkingaboutlambdafunctions?Like
f=lambdax:x**2+2*x5

Thosethingsareactuallyquiteuseful.Pythonsupportsastyleofprogrammingcalledfunctional
programmingwhereyoucanpassfunctionstootherfunctionstodostuff.Example:
mult3=filter(lambdax:x%3==0,[1,2,3,4,5,6,7,8,9])

sets mult3 to [3,6,9] ,thoseelementsoftheoriginallistthataremultiplesof3.Thisisshorter


(and,onecouldargue,clearer)than
deffilterfunc(x):
returnx%3==0
mult3=filter(filterfunc,[1,2,3,4,5,6,7,8,9])

Ofcourse,inthisparticularcase,youcoulddothesamethingasalistcomprehension:
mult3=[xforxin[1,2,3,4,5,6,7,8,9]ifx%3==0]

(orevenas range(3,10,3) )butthereareothercases,likeconstructingfunctionsasreturn


valuesfromotherfunctions,whereyoucan'tusealistcomprehensionandalambdafunction
maybetheshortestwaytowritesomethingout.Like
deftransform(n):
returnlambdax:x+n
f=transform(3)

http://stackoverflow.com/questions/890128/whyarepythonlambdasuseful

1/13

03/12/2015

WhyarePythonlambdasuseful?StackOverflow

f(4)#is7

Iuselambdafunctionsonaregularbasis.IttookawhiletogetusedtothembutonceIdidI'm
gladPythonhasthem)
editedJul7'10at1:13

answeredMay20'09at20:52
DavidZ
60.8k

135

181

72 lambdaisoneoftherequisitesforareadablefunctionallanguage.it'sapitythatPython'ssyntaxmakes
themsolimited.still,it'smilesaheadofanylanguagewithoutit.JavierMay20'09at21:13
11 @Xavier:IbelieveJavierisreferringtoverbosityofthe lambda keyboard,andpossiblythefactthatyou
canonlyuseexpressionsinPythonlambdas.ContrastC#: x=>... ,orHaskell: \x>... with
Python lambdax:... .Porges Jul7'10at1:18
62 @Porges:Theverbosityisaminorproblem.ThefactthtayoucanonlyuseaSINGLEexpression(andno
statements)isafarmoreseriousproblem.JUSTMYcorrectOPINIONJul7'10at1:37
5

@orokusaki:infunctionallanguages,lambdaisthebasicformoffunctiondefinition,anyfuncionisin
principlealambdaassignedtoavariable.inPythonsyntax,thelambdaformdoesn'tallowarbitrary
functions,justasingleexpression.themainreasonissothatitdoesn'tneedan'end'marker.Javier
Nov5'10at17:30

12 Arbitrarilycomplexlambdasareagreatwaytoproducedisgustingblobsofcodegolfcode,butterriblein
reality.EveninfunctionallanguagesI'vefoundIgravitatetowardsnamingthingswhereverIcantoavoid
mycodebecominganunreadablemess.Lambdasstopyoureusingcode,andtheycramalotintoa
singleline.Yes,insimplecases,theyareuseful,butthenasingleexpressionisalmostallyouever
need.Pythonprovidessyntacticsugarforalotofthecasesyou'dwantthemanyway.Inmorecomplex
case,justdefineanamedfunctionanduseit.Latty Nov18'14at23:35

lambda isjustafancywayofsaying function .Otherthanitsname,thereisnothingobscure,


intimidatingorcrypticaboutit.Whenyoureadthefollowingline,replace lambda by function in
yourmind:
>>>f=lambdax:x+1
>>>f(3)
4

Itjustdefinesafunctionof

.Someotherlanguages,like

,sayitexplicitly:

>f=function(x){x+1}
>f(3)
4

Yousee?It'soneofthemostnaturalthingstodoinprogramming.
answeredJan16'10at15:03
user251650
881

Alambdaispartofaveryimportantabstractionmechanismwhichdealswithhigherorder
functions.Togetproperunderstandingofitsvalue,pleasewatchhighqualitylessonsfrom
AbelsonandSussman,andreadthebookSICP
Thesearerelevantissuesinmodernsoftwarebusiness,andbecomingevermorepopular.
answeredMay20'09at20:49
egaga
7,699

35

48

42 +1forSICP.Everyoneshouldreadthatbook.Ifitdoesn'tkillyouitWILLmakeyoustronger.Trey May
20'09at20:59
1

Lambdaexpressionsarebecomingpopularinotherlanguages(likeC#)aswell.They'renotgoing
anywhere.ReadinguponclosureswouldbeausefulexercisetounderstandLambdas.Closuresmakea
lotofcodingmagicpossibleinframeworkslikejQuery.DanEsparzaMay20'09at21:36

Thispostdoesnotcontainananswer.Itwouldfitbetterasacomment.joarNov11'11at14:05

20 IfyouneedtoreadabookeverytimeyouaskaquestiononSO,it'sgoingtogetugly.esatis Aug21'12
at6:50
14 readSICPtounderstandpythonlambda?uff..DanielMagnussonJan10'13at8:50

http://stackoverflow.com/questions/890128/whyarepythonlambdasuseful

2/13

03/12/2015

WhyarePythonlambdasuseful?StackOverflow

Thetwolinesummary:
1. Closures :Veryuseful.Learnthem,usethem,lovethem.
2. Python's lambda keyword:unnecessary,occasionallyuseful.Ifyoufindyourselfdoing
anythingremotelycomplexwithit,putitawayanddefinearealfunction.
answeredMay20'09at22:37
JohnFouhy
19.1k

44

63

Ifeelthisisthecorrectanswer.ostler.c Nov17at23:28

Idoubtlambdawillgoaway.SeeGuido'spostaboutfinallygivinguptryingtoremoveit.Alsosee
anoutlineoftheconflict.
YoumightcheckoutthispostformoreofahistoryaboutthedealbehindPython'sfunctional
features:http://pythonhistory.blogspot.com/2009/04/originsofpythonsfunctionalfeatures.html
Curiously,themap,filter,andreducefunctionsthatoriginallymotivatedtheintroductionof
lambdaandotherfunctionalfeatureshavetoalargeextentbeensupersededbylist
comprehensionsandgeneratorexpressions.Infact,thereducefunctionwasremovedfrom
listofbuiltinfunctionsinPython3.0.(However,it'snotnecessarytosendincomplaintsabout
theremovaloflambda,maporfilter:theyarestaying.:)
Myowntwocents:Rarelyislambdaworthitasfarasclaritygoes.Generallythereisamore
clearsolutionthatdoesn'tincludelambda.
editedJul30'14at23:44

answeredMay20'09at20:46

leewangzhong

rhettg

1,296

1,657

17

10

15

2 notethatreduceisstillimportableinPython3.0.IfYouREALLYwantit,Youcanstillhaveit.ReefMay
20'09at22:00
2 +1forthelinktoGuido'sadmittanceofdefeat.It'snicetoseesomanypostersagreeingwith lambda !
new123456Jun15'11at17:44
IthinkGuido'sattemptwasmoreaboutthesyntax.Thispersonalsothinksthat:
cackhanded.com/blog/post/2008/01/24/leewangzhongJul30'14at23:45

lambdasareextremelyusefulinGUIprogramming.Forexample,letssayyou'recreatingagroup
ofbuttonsandyouwanttouseasingleparamaterizedcallbackratherthanauniquecallbackper
button.Lambdaletsyouaccomplishthatwithease:
forvaluein["one","two","three"]:
b=tk.Button(label=value,command=lambdaarg=value:my_callback(arg))
b.pack()

Thealternativeistocreateaseparatecallbackforeachbuttonwhichcanleadtoduplicated
code.
answeredApr24'11at16:48
BryanOakley
107k

11

111

194

ThisisexactlywhyIlookedupwhatlambdawas,butwhydoesthiswork,tomeitlookstheexactsame
asjustcallingthefunctionstraight(stackoverflow.com/questions/3704568/).Maybeit'slate,itdoes
work,butwhydoesitwork?Rqomey Aug5'13at22:10
@Rqomey:thedifferenceisthatinthisexample value isdefinedinaloopintheotherexamplethe
parameteralwaysonlyhadonevalue.Whenyouaddsomethinglike arg=value ,youareattachingthe
currentvaluetothecallback.Withoutit,youbindareferencetothevariableinthecallback.Thereference
willalwayscontainthefinalvalueofthevariable,sincethecallbackhappenssometimeaftertheloophas
alreadyfinishedrunning.BryanOakley Aug6'13at1:56
1 Ijustgotthisworkingyesterday,Ihonestlycan'tbelievehowusefulitis...Icanbuildupamenufromone
forloopandacsvfileforconfiguration.Reallyusefulstuff.Rqomey Aug7'13at8:31
1 Notetheexistenceof functools.partial() whichallowsyoutodothiswithlesscruft(andwithout

http://stackoverflow.com/questions/890128/whyarepythonlambdasuseful

3/13

03/12/2015

WhyarePythonlambdasuseful?StackOverflow

lambda ). Latty Nov18'14at23:40

2 partial(my_callback,value) vs lambdaarg=value:my_callback(arg) thelambdahasmuchmore


cruft(assignmenttoargandthenusage)andit'slessclearwhattheintentionis(youcouldbedoing
somethingsubtlydifferentinthelambda).Importsarenotreallyaproblem(youhaveapileanywayandit's
onceperfile).Codeisbestjudgedonhowwellitreads,and partial() ismucheasiertoreadthanthe
lambda.Latty Nov19'14at10:12

Prettymuchanythingyoucandowith
listandgeneratorexpressions.

lambda

youcandobetterwitheithernamedfunctionsor

Consequently,forthemostpartyoushouldjustoneofthoseinbasicallyanysituation(except
maybeforscratchcodewrittenintheinteractiveinterpreter).
answeredMay20'09at20:45
AaronMaenpaa
46.9k

75

97

"forthemostpartyoushouldjustoneofthoseinbasicallyanysituation"Period.Typinglambda'sinthe
interpreterisn'teventhathelpful.S.LottMay20'09at20:58

10 @JavierIagreewithyouifyouaretalkingabout"lambda"theconcepthowever,ifwe'retalkingabout
"lambda"thepythonkeywordthen:1)namedfunctionsarefasterandcandomore
(statements+expressions)almostanywhereyouwoulduselambdas(map+filter)youcanjustgenerator
expressionsorlistcomprehensionswhicharemoreperformantandconcise.I'mnotsayingthatfirstclass
functionsaren'tcool,justthatthe"lambda"keywordinpythonisn'tasgoodasjustusinganamed
function,that'sall.AaronMaenpaaMay20'09at22:05
3

lambdahasbeenindispensabletomeforusewithfunctionsthattakecallbackargumentslikethekey=
argumenttosort()andsorted()RickCopelandMay21'09at15:57

11 @RickIdon'tdoubtthat,buttherealityisifwhenyousee"lambda"andyouthink"zohmygodlambda"
andstartwritingschemecodeinpythonyouwillsurlybedisappointingbythelimitationsofpython's
lambdaexpression.Ontheotherhand,ifyoustartoutthinkingtoyourself"Willalistcomprehension
work?No.WillwhatIneedbenifitfrombeinganamedfunction?No.Okayfine:sorted(xs,key=lambda
x:x.name,x.height)",youwillprobablyendupusinglambdatherightnumberoftimes.AaronMaenpaa
May21'09at17:02
3

+1:Icannotstressthatenoughwhenoneusesalambdaoneusesannamelessfunction.Andnamesdo
haveapreciousintellectualaddedvalue.StephaneRollandNov15'12at12:38

Ifindlambdausefulforalistoffunctionsthatdothesame,butfordifferentcircumstances.Like
themozillapluralrules .
plural_rules=[
lambdan:'all',
lambdan:'singular'ifn==1else'plural',
lambdan:'singular'if0<=n<=1else'plural',
...
]
#Callpluralrule#1withargument4tofindoutwhichsentenceformtouse.
plural_rule[1](4)#returns'plural'

Ifyou'dhavetodefineafunctionforallofthoseyou'dgomadbytheendofit.Alsoitwouldn'tbe
nicewithfunctionnameslikeplural_rule_1,plural_rule_2,etc.Andyou'dneedtoeval()itwhen
you'redependingonavariablefunctionid.
editedJan16'10at15:50

answeredJan16'10at15:43
TorValamo
17.9k

45

66

ThislookssimilartothebriefencountersthatI'vehadsofarinF#withpatternmatchingandoptions.Do
youhavemoreinfoabouthowtousethissyntax?KennethPosey Jun8'11at18:29

I'vebeenusingPythonforafewyearsandI'veneverrunintoacasewhereI'veneededlambda.
Really,asthetutorialstates,it'sjustforsyntacticsugar.
answeredMay20'09at20:47
MattSchmidt
562

http://stackoverflow.com/questions/890128/whyarepythonlambdasuseful

4/13

03/12/2015

WhyarePythonlambdasuseful?StackOverflow

4 Theyarevery usefulwhendevelopingaGUIusingpython.Often,widgetsneedareferencetoafunction.If
youneedawidgettocallafunctionandpassarguments,lambdaisaveryconvenientwaytodothat.
BryanOakley Apr24'11at16:38

Ican'tspeaktopython'sparticularimplementationoflambda,butingenerallambdafunctionsare
reallyhandy.They'reacoretechnique(maybeevenTHEtechnique)offunctionalprogramming,
andthey'realsoveryuseufulinobjectorientedprograms.Forcertaintypesofproblems,they're
thebestsolution,socertainlyshouldn'tbeforgotten!
Isuggestyoureaduponclosures andthemapfunction(thatlinkstopythondocs,butitexistsin
nearlyeverylanguagethatsupportsfunctionalconstructs)toseewhyit'suseful.
answeredMay20'09at20:45
rmeador
16.9k

12

39

81

1 Thatstuffcanbedonewithoutlambdas.It'sjustabighassle.BrianMay20'09at20:54

InPython,

lambda

isjustawayofdefiningfunctionsinline,

a=lambdax:x+1
printa(1)

and..
defa(x):returnx+1
printa(1)

..aretheexactsame.
ThereisnothingyoucandowithlambdawhichyoucannotdowitharegularfunctioninPython
functionsareanobjectjustlikeanythingelse,andlambdassimplydefineafunction:
>>>a=lambdax:x+1
>>>type(a)
<type'function'>

IhonestlythinkthelambdakeywordisredundantinPythonIhaveneverhadtheneedtouse
them(orseenoneusedwherearegularfunction,alistcomprehensionoroneofthemanybuiltin
functionscouldhavebeenbetterusedinstead)
Foracompletelyrandomexample,fromthearticle"Pythonslambdaisbroken!":
Toseehowlambdaisbroken,trygeneratingalistoffunctions
fi(n)=i+n .Firstattempt:

fs=[f0,...,f9]

where

fs=[(lambdan:i+n)foriinrange(10)]fs313

Iwouldargue,evenifthatdidwork,it'shorriblyand"unpythonic",thesamefunctionalitycouldbe
writtenincountlessotherways,forexample:
>>>n=4
>>>[i+nforiinrange(10)]
[4,5,6,7,8,9,10,11,12,13]

Yes,it'snotthesame,butIhaveneverseenacausewheregeneratingagroupoflambda
functionsinalisthasbeenrequired..Itmightmakesenseinotherlanguages,butPythonisnot
Haskell(orLisp,or...)
Pleasenotethatwecanuselambdaandstillachievethedesiredresultsinthisway:
>>>fs=[(lambdan,i=i:i+n)foriinrange(10)]
>>>fs[3](4)
7

Edit:
http://stackoverflow.com/questions/890128/whyarepythonlambdasuseful

5/13

03/12/2015

WhyarePythonlambdasuseful?StackOverflow

Thereareafewcaseswherelambdaisuseful,forexampleit'softenconvenientwhenconnecting
upsignalsinPyQtapplications,likethis:
w=PyQt4.QtGui.QLineEdit()
w.textChanged.connect(lambdaevent:dothing())

Justdoing w.textChanged.connect(dothing) wouldcallthe dothing methodwithanextra event


argumentandcauseanerror..Usingthelambdameanswecantidilydroptheargumentwithout
havingtodefineawrappingfunction
editedSep13at14:04

answeredMay21'09at2:03

Sonu

dbr

82.2k

41

205

282

your"lambdaisbroken"argumentisbroken,becauseofthepythonvariablescopingrulesworkthatway,
period.Youwillbebittenthesamewayifyoucreatedaclosureinsideforloop.AnttiHaapalaFeb27'13
at7:24
lambdaisjustpython'swaytoprovidetheuserwithan"anonymous"function,likemanyotherlanguages
have(e.g.,javascript).StefanGruenwaldOct31'14at19:27
Thelambdaandfunction a 'sthatyoudefinedarenotexactly same.:)Theydifferby __name__ fieldat
least...progoNov6'14at7:55
It'sworksmorethanjustaninlinefunction.ktaNov28at12:23

Asstatedabove,thelambdaoperatorinPythondefinesananonymousfunction,andinPython
functionsareclosures.Itisimportantnottoconfusetheconceptofclosureswiththeoperator
lambda,whichismerelysyntacticmethadoneforthem.
WhenIstartedinPythonafewyearsago,Iusedlambdasalot,thinkingtheywerecool,along
withlistcomprehensions.However,IwroteandhavetomaintainabigwebsitewritteninPython,
withontheorderofseveralthousandfunctionpoints.I'velearntfromexperiencethatlambdas
mightbeOKtoprototypethingswith,butoffernothingoverinlinefunctions(namedclosures)
exceptforsavingafewkeystokes,orsometimesnot.
Basicallythisboilsdowntoseveralpoints:
itiseasiertoreadsoftwarethatisexplicitlywrittenusingmeaningfulnames.Anonymous
closuresbydefinitioncannothaveameaningfulname,astheyhavenoname.Thisbrevity
seems,forsomereason,toalsoinfectlambdaparameters,henceweoftenseeexamples
likelambdax:x+1
itiseasiertoreusenamedclosures,astheycanbereferredtobynamemorethanonce,
whenthereisanametorefertothemby.
itiseasiertodebugcodethatisusingnamedclosuresinsteadoflambdas,becausethe
namewillappearintracebacks,andaroundtheerror.
That'senoughreasontoroundthemupandconvertthemtonamedclosures.However,Ihold
twoothergrudgesagainstanonymousclosures.
Thefirstgrudgeissimplythattheyarejustanotherunnecessarykeywordclutteringupthe
language.
Thesecondgrudgeisdeeperandontheparadigmlevel,i.e.Idonotlikethattheypromotea
functionalprogrammingstyle,becausethatstyleislessflexiblethanthemessagepassing,
objectorientedorproceduralstyles,becausethelambdacalculusisnotTuringcomplete(luckily
inPython,wecanstillbreakoutofthatrestrictioneveninsidealambda).ThereasonsIfeel
lambdaspromotethisstyleare:
Thereisanimplicitreturn,i.e.theyseemlikethey'should'befunctions.
Theyareanalternativestatehidingmechanismtoanother,moreexplicit,morereadable,
morereusableandmoregeneralmechanism:methods.
ItryhardtowritelambdafreePython,andremovelambdasonsight.IthinkPythonwouldbea
slightlybetterlanguagewithoutlambdas,butthat'sjustmyopinion.
answeredOct18'10at18:01
MikeA
897

11

1 "...inPythonfunctionsareclosures".That'snotquiteright,asIunderstandit.Closuresarefunctions,but

http://stackoverflow.com/questions/890128/whyarepythonlambdasuseful

6/13

03/12/2015

WhyarePythonlambdasuseful?StackOverflow

functionsarenotalwaysclosures.Function>lambdax,y:x+y.Closure>lambdax:lambday:x+y
OatmanSep14'11at15:57
4 "becausethelambdacalculusisnotTuringcomplete"isplainwrong,untypedlambdacalculusISTuring
complete,thatisthereasonwhyitissosignificant.YoucangetrecursionusingtheYcombinator, Y=
lambdaf:(lambdax:x(x))(lambday:f(lambda*args:y(y)(*args))) AnttiHaapala Feb27'13at
7:50
Furthermore,ifonegoestoWikipediatoreadonTuringcompleteness,itsays"Aclassicexampleisthe
lambdacalculus."AnttiHaapalaFeb27'13at7:56
4 GoodLord,answerthatclaimslambdacalculusisnotTuringcompletewith10upvotes?!Marcino Sep
10'13at13:52
seriouslyNotTuringcompletethisanswerneedsaseriouseditorretraction.TonySuffolk66Feb16at
12:11

Lambdasareactuallyverypowerfulconstructsthatstemfromideasinfunctionalprogramming,
anditissomethingthatbynomeanswillbeeasilyrevised,redefinedorremovedinthenear
futureofPython.Theyhelpyouwritecodethatismorepowerfulasitallowsyoutopass
functionsasparameters,thustheideaoffunctionsasfirstclasscitizens.
Lambdasdotendtogetconfusing,butonceasolidunderstandingisobtained,youcanwrite
cleanelegantcodelikethis:
squared=map(lambdax:x*x,[1,2,3,4,5])

Theabovelineofcodereturnsalistofthesquaresofthenumbersinthelist.Ofcourse,youcould
alsodoitlike:
defsquare(x):
returnx*x
squared=map(square,[1,2,3,4,5])

Itisobvioustheformercodeisshorter,andthisisespeciallytrueifyouintendtousethemap
function(oranysimilarfunctionthattakesafunctionasaparameter)inonlyoneplace.Thisalso
makesthecodemoreintuitiveandelegant.
Also,as@DavidZaslavskymentionedinhisanswer,listcomprehensionsarenotalwaysthe
waytogoespeciallyifyourlisthastogetvaluesfromsomeobscuremathematicalway.
Fromamorepracticalstandpoint,oneofthebiggestadvantagesoflambdasformerecentlyhas
beeninGUIandeventdrivenprogramming.IfyoutakealookatcallbacksinTkinter,allthey
takeasargumentsaretheeventthattriggeredthem.E.g.
defdefine_bindings(widget):
widget.bind("<Button1>",dosomethingcool)
defdosomethingcool(event):
#Yourcodetoexecuteontheeventtrigger

Nowwhatifyouhadsomeargumentstopass?Somethingassimpleaspassing2argumentsto
storethecoordinatesofamouseclick.Youcaneasilydoitlikethis:
defmain():
#definewidgetsandotherimpstuff
x,y=None,None
widget.bind("<Button1>",lambdaevent:dosomethingcool(x,y))
defdosomethingcool(event,x,y):
x=event.x
y=event.y
#Doothercoolstuff

Nowyoucanarguethatthiscanbedoneusingglobalvariables,butdoyoureallywanttobang
yourheadworryingaboutmemorymanagementandleakageespeciallyiftheglobalvariablewill
justbeusedinoneparticularplace?Thatwouldbejustpoorprogrammingstyle.
Inshort,lambdasareawesomeandshouldneverbeunderestimated.Pythonlambdasarenotthe
sameasLISPlambdasthough(whicharemorepowerful),butyoucanreallydoalotofmagical
stuffwiththem.
answeredMay24'13at13:02
varagrawal
764

http://stackoverflow.com/questions/890128/whyarepythonlambdasuseful

21

7/13

03/12/2015

WhyarePythonlambdasuseful?StackOverflow

Thanks.Icompletelydidn'tunderstandyourlastexample.Howcomexandyaredefinedinboth main and


do_something_cool ?Whathappensto x and y inthefunction?Thevaluespassedseemtobe
immediatelyoverwritten?Howdoesthefunctionknowabout event ?Couldyouaddsomecomments/
explanation?Thanks SanjayManoharApr9at21:03
@SanjayManoharIampassing x and y asargumentsto dosomethingcool andtheirvaluesarebeing
setinthefunctiontoillustratehowyoucanuselambdastopassargumentswherenoneareexpected.The
widget.bind functionexpectsa event parameterwhichidentifiestheGUIeventonthatparticular
widget.IrecommendreadingonTkinter'sprogrammingmodelforgreaterclarity.varagrawalApr10at5:08
hmmIthinkIunderstandtheTkintermodel.Butstilldon'tquiteunderstandyoupass x,y thendo
x=event.x .Doesn'tthatoverwritethevalueyoupassed?Andhowdoesthefunctionknowwhat event
is?Idon'tseewhereyoupassthattothefunction.Orisitamethod?Alsoareyouallowedminussignsina
functionname?SanjayManoharApr10at18:37
@SanjayManoharbuddyyouneedtoreaduponTkinterandPython.Tkinterpassestheeventobjectthe
functionasadefaultaction.Asforthe x,y ,thatisjustanexampleforillustrativepurposes.Iamtrying
toshowthepoweroflambdas,notTkinter.:)varagrawalApr15at14:48
OKnowIseewhatyouintendedyouwantthefunctiontoreceive event ?inthatcase,shouldn'tyour
lambdaread lambdaevent:do_something_cool(event,x,y) ?SanjayManoharApr16at21:57

Oneofthenicethingsabout lambda that'sinmyopinionunderstatedisthatit'swayofdeferring


anevaluationforsimpleformstillthevalueisneeded.Letmeexplain.
Manylibraryroutinesareimplementedsothattheyallowcertainparameterstobecallables(of
whomlambdaisone).Theideaisthattheactualvaluewillbecomputedonlyatthetimewhenit's
goingtobeused(ratherthatwhenit'scalled).An(contrived)examplemighthelptoillustratethe
point.Supposeyouhavearoutinewhichwhichwasgoingtodologagiventimestamp.Youwant
theroutinetousethecurrenttimeminus30minutes.You'dcallitlikeso
log_timestamp(datetime.datetime.now()datetime.timedelta(minutes=30))

Nowsupposetheactualfunctionisgoingtobecalledonlywhenacertaineventoccursandyou
wantthetimestamptobecomputedonlyatthattime.Youcandothislikeso
log_timestamp(lambda:datetime.datetime.now()datetime.timedelta(minutes=30))

Assumingthe log_timestamp canhandlecallableslikethis,itwillevaluatethiswhenitneedsit


andyou'llgetthetimestampatthattime.
Thereareofcoursealternatewaystodothis(usingthe
I'veconveyedthepoint.

operator

moduleforexample)butIhope

Update:Hereisaslightlymoreconcreterealworldexample.
Update2:Ithinkthisisanexampleofwhatiscalledathunk .
editedOct29at3:37

answeredJan16'10at15:30
NoufalIbrahim
39.6k

70

114

Lambdafunctionit'sanonbureaucraticwaytocreateafunction.
That'sit.Forexample,let'ssuposeyouhaveyourmainfunctionandneedtosquarevalues.Let's
seethetraditionalwayandthelambdawaytodothis:
Traditionalway:
defmain():
...
...
y=square(some_number)
...
returnsomething
defsquare(x):
returnx**2

Thelambdaway:
defmain():
...
square=lambdax:x**2
y=square(some_number)
returnsomething

http://stackoverflow.com/questions/890128/whyarepythonlambdasuseful

8/13

03/12/2015

WhyarePythonlambdasuseful?StackOverflow

Seethedifference?
Lambdafunctionsgoverywellwithlists,likelistscomprehensionsormap.Infact,list
comprehensionit'sa"pythonic"waytoexpressyourselfusinglambda.Ex:
>>>a=[1,2,3,4]
>>>[x**2forxina]
[1,4,9,16]

Let'sseewhateachelementsofthesyntaxmeans:
[]:"Givemealist"
x**2:"usingthisnewbornfunction"
forxina:"intoeachelementina"
That'sconvenientuh?Creatingfunctionslikethis.Let'srewriteitusinglambda:
>>>square=lambdax:x**2
>>>[square(s)forxina]
[1,4,9,16]

Nowlet'susemap,whichisthesamething,butmorelanguageneutral.Mapstakes2arguments:
(i)onefunction
(ii)aniterable
Andgivesyoualistwhereeachelementit'sthefunctionappliedtoeachelementoftheiterable.
So,usingmapwewouldhave:
>>>a=[1,2,3,4]
>>>squared_list=map(lambdax:x**2,a)

Ifyoumasterlambdasandmapping,youwillhaveagreatpowertomanipulatedataandina
conciseway.Lambdafunctionsareneitherobscurenortakeawaycodeclarity.Don'tconfuse
somethinghardwithsomethingnew.Onceyoustartusingthem,youwillfinditveryclear.
editedSep1at19:31

answeredOct11'13at3:03

Mark
2,515

LucasRibeiro
10

25

1,578

11

14

Firstcongratsthatmanagedtofigureoutlambda.Inmyopinionthisisreallypowerfulconstructto
actwith.Thetrendthesedaystowardsfunctionalprogramminglanguagesissurelyanindicator
thatitneithershouldbeavoidednoritwillberedefinedinthenearfuture.
Youjusthavetothinkalittlebitdifferent.I'msuresoonyouwillloveit.Butbecarefulifyoudeal
onlywithpython.Becausethelambdaisnotarealclosure,itis"broken"somehow:pythons
lambdaisbroken
editedApr2'13at11:01

answeredMay20'09at20:47

Anthon
7,883

NorbertHartl
12

34

62

5,475

21

41

Python'slambdaisnotbroken.Therearetwowaystohandlelocalsinlambdas.Bothhaveadvantagesand
disadvantages.IthinktheapproachPython(andC#)tookisprobablycounterintuitivetothosemore
accustomedtopurelyfunctionallanguages,sincewithapurelyfunctionallanguageIdon'tthinkthat
approachevenmakessense.BrianMay20'09at20:54
Itisindeedcounterintuitive.I'mnotapythonprogrammerbutinsqueaksmalltalkitisthesameandI
stumpleuponthisregularly.SoevenIwouldconsiderit"broken":)NorbertHartlMay20'09at21:02
No,thishasnothingtodowithcounterintuitivity.Itisjustthatthelexicalscopeofvariablenamesisthatof
afunctionaloopdoesnotintroducealexicalscope.FunctionsalsoworkthesamewayinJavascript.If
youneedascopeforvar,youcanalwaysdo(lambdascopedvar:lambdax:scopedvar+x)()
AnttiHaapalaFeb27'13at7:26

Lambdasaredeeplylikedtofunctionalprogrammingstyleingeneral.Theideathatyoucansolve
problemsbyapplyingafunctiontoadata,andmergingtheresults,iswhatgoogleusesto
implementmostofitsalgorithms.Programswritteninfunctionalrpogrammingstyle,areeasily
http://stackoverflow.com/questions/890128/whyarepythonlambdasuseful

9/13

03/12/2015

WhyarePythonlambdasuseful?StackOverflow

parrallelizedandhencearebecomingmoreandmoreimportantwithmodernmultiucore
machiines.Soinshort,NOyoushouldnotforgetthem.
answeredMay20'09at20:46
Yogi
1,278

10

16

I'mjustbeginningPythonandranheadfirstintoLambdawhichtookmeawhiletofigureout.
Notethatthisisn'tacondemnationofanything.Everybodyhasadifferentsetofthingsthatdon't
comeeasily.
Islambdaoneofthose'interesting'languageitemsthatinreallifeshouldbeforgotten?
No.
I'msuretherearesomeedgecaseswhereitmightbeneeded,butgiventheobscurityofit,
It'snotobscure.Thepast2teamsI'veworkedon,everybodyusedthisfeatureallthetime.
thepotentialofitbeingredefinedinfuturereleases(myassumptionbasedonthevarious
definitionsofit)
I'veseennoseriousproposalstoredefineitinPython,beyondfixingtheclosuresemanticsafew
yearsago.
andthereducedcodingclarityshoulditbeavoided?
It'snotlessclear,ifyou'reusingitright.Onthecontrary,havingmorelanguageconstructs
availableincreases clarity.
Thisremindsmeofoverflowing(bufferoverflow)ofCtypespointingtothetopvariableand
overloadingtosettheotherfieldvalues...sortofatechieshowmanshipbutmaintenancecoder
nightmare..
Lambdaislikebufferoverflow?Wow.Ican'timaginehowyou'reusinglambdaifyouthinkit'sa
"maintenancenightmare".
answeredMay20'09at20:57
Ken
847

12

5 1formakingme(andothers)readthewholequestionagain.Notethatothersmanagedtoanswerwithout
doingit.ReefMay20'09at22:03

IstartedreadingDavidMertz'sbooktoday'TextProcessinginPython.'Whilehehasafairly
tersedescriptionofLambda'stheexamplesinthefirstchaptercombinedwiththeexplanationin
AppendixAmadethemjumpoffthepageforme(finally)andallofasuddenIunderstoodtheir
value.ThatisnottosayhisexplanationwillworkforyouandIamstillatthediscoverystagesoI
willnotattempttoaddtotheseresponsesotherthanthefollowing:IamnewtoPythonIamnew
toOOPLambdaswereastruggleformeNowthatIreadMertz,IthinkIgetthemandIseethem
asveryusefulasIthinktheyallowacleanerapproachtoprogramming.
HereproducestheZenofPython,onelineofwhichisSimpleisbetterthancomplex.Asanon
OOPprogrammerreadingcodewithlambdas(anduntillastweeklistcomprehensions)Ihave
thoughtThisissimple?.Ifinallyrealizedtodaythatactuallythesefeaturesmakethecodemuch
morereadable,andunderstandablethanthealternativewhichisinvariablyaloopofsomesort.I
alsorealizedthatlikefinancialstatementsPythonwasnotdesignedforthenoviceuser,ratherit
isdesignedfortheuserthatwantstogeteducated.Ican'tbelievehowpowerfulthislanguageis.
Whenitdawnedonme(finally)thepurposeandvalueoflambdasIwantedtoripupabout30
programsandstartoverputtinginlambdaswhereappropriate.
answeredMay21'09at1:08
PyNEwbie
2,282

http://stackoverflow.com/questions/890128/whyarepythonlambdasuseful

16

47

10/13

03/12/2015

WhyarePythonlambdasuseful?StackOverflow

IcangiveyouanexamplewhereIactuallyneededlambdaserious.I'mmakingagraphical
program,wheretheuserightclicksonafileandassignsitoneofthreeoptions.Itturnsoutthatin
Tkinter(theGUIinterfacingprogramI'mwritingthisin),whensomeonepressesabutton,itcan't
beassignedtoacommandthattakesinarguments.SoifIchoseoneoftheoptionsandwanted
theresultofmychoicetobe:
print'hithere'
Thennobigdeal.ButwhatifIneedmychoicetohaveaparticulardetail.Forexample,ifIchoose
choiceA,itcallsafunctionthattakesinsomeargumentthatisdependentonthechoiceA,Bor
C,TKintercouldnotsupportthis.Lamdawastheonlyoptiontogetaroundthisactually...
answeredJul13'11at23:05
Glueberg
41

Well,presumablyyoucouldhavedone deffoo... andthenpassedin foo insteadof lambda .It'sjust


morecodeandyouhavetocomeupwithaname.JonCoombs Dec2'14at1:39

Iuseitquiteoften,mainlyasanullobjectortopartiallybindparameterstoafunction.
Hereareexamples:

toimplementnullobjectpattern:
{

DATA_PACKET:self.handle_data_packets

NET_PACKET:self.handle_hardware_packets
}.get(packet_type,lambdax:None)(payload)

forparameterbinding:
letsaythatIhavethefollowingAPI
defdump_hex(file,var)
#somecode

pass
classX(object):
#...

defpacket_received(data):

#somekindofpreprocessing

self.callback(data)
#...

Then,whenIwan'ttoquicklydumptherecieveddatatoafileIdothat:
dump_file=file('hex_dump.txt','w')
X.callback=lambda(x):dump_hex(dump_file,x)
...
dump_file.close()

answeredMay20'09at21:20
PiotrCzapla
10.2k

12

65

92

Ausefulcaseforusinglambdasistoimprovethereadabilityoflonglistcomprehensions.In
thisexample loop_dic isshortforclaritybutimagine loop_dic beingverylong.Ifyouwouldjust
useaplainvaluethatincludes i insteadofthelambdaversionofthatvalueyouwouldgeta
NameError .
>>>lis=[{"name":"Peter"},{"name":"Josef"}]
>>>loop_dic=lambdai:{"name":i["name"]+"Wallace"}
>>>new_lis=[loop_dic(i)foriinlis]
>>>new_lis
[{'name':'PeterWallace'},{'name':'JosefWallace'}]

Insteadof
>>>lis=[{"name":"Peter"},{"name":"Josef"}]

http://stackoverflow.com/questions/890128/whyarepythonlambdasuseful

11/13

03/12/2015

WhyarePythonlambdasuseful?StackOverflow

>>>new_lis=[{"name":i["name"]+"Wallace"}foriinlis]
>>>new_lis
[{'name':'PeterWallace'},{'name':'JosefWallace'}]

editedNov3'12at12:35

answeredNov3'12at12:25
Bentley4
2,728

32

82

Iuselambdastoavoidcodeduplication.Itwouldmakethefunctioneasily
comprehensibleEg:
defa_func()
...
ifsome_conditon:
...
call_some_big_func(arg1,arg2,arg3,arg4...)
else
...
call_some_big_func(arg1,arg2,arg3,arg4...)

Ireplacethatwithatemplambda
defa_func()
...
call_big_f=lambdaargs_that_change:call_some_big_func(arg1,arg2,arg3,
args_that_change)
ifsome_conditon:
...
call_big_f(argX)
else
...
call_big_f(argY)

answeredOct9'13at0:29
balki
5,957

32

65

Iuse lambda tocreatecallbacksthatincludeparameters.It'scleanerwritingalambdainoneline


thantowriteamethodtoperformthesamefunctionality.
Forexample:
importimported.module
deffunc():
returnlambda:imported.module.method("foo","bar")

asopposedto:
importimported.module
deffunc():
defcb():
returnimported.module.method("foo","bar")
returncb

answeredJan3'14at18:31
NuclearPeon
1,416

13

20

I'mapythonbeginner,sotogetteraclearideaoflambdaIcompareditwitha'for'loopintermsof
efficiency.Here'sthecode(python2.7)
importtime
start=time.time()#Measurethetimetakenforexecution
deffirst():
squares=map(lambdax:x**2,range(10))
#^Lambda
end=time.time()
elapsed=endstart
printelapsed+'seconds'
returnelapsed#gives0.0seconds

http://stackoverflow.com/questions/890128/whyarepythonlambdasuseful

12/13

03/12/2015

WhyarePythonlambdasuseful?StackOverflow

defsecond():
lst=[]
foriinrange(10):
lst.append(i**2)
#^a'for'loop
end=time.time()
elapsed=endstart
printelapsed+'seconds'
returnelapsed#gives0.0019998550415seconds.
printabs(second()first())#Gives0.0019998550415seconds!(duh)

editedFeb7'14at16:26

answeredFeb6'14at18:43
user3252158
41

5 Youmaybeinterestedinthe timeit module,whichtypicallygivesmoreaccurateresultsthansubtracting


time.time() values. Kevin Feb6'14at19:15
1 Hmm,don'tyouneedtorestartyourtimeratthestartoffirst()andsecond()?qneillMay14at0:47

Lambdaisaprocedureconstructor.Youcansynthesizeprogramsatruntime,althoughPython's
lambdaisnotverypowerful.Notethatfewpeopleunderstandthatkindofprogramming.
answeredMay20'09at20:52
NickDandoulakis
29.9k

http://stackoverflow.com/questions/890128/whyarepythonlambdasuseful

10

68

113

13/13

Das könnte Ihnen auch gefallen