What are lambdas for?

I understand what they do and how to use them, but I'm still somewhat confused about why they are included in Python. What is the use of using them in a standard style for defining a function?

The only real difference I can think of is that you can create them inside an expression. For example, if myList was an int list and you wanted to add it to each element, you can use

list(map(lambda x: x+1, myList)) 

If you want to do this using function definitions, you will have to define it elsewhere, and then pass this variable.

However, I seriously doubt that this relatively small convenience would justify their inclusion in the language, so I assume that something is missing for me there. Or perhaps I underestimate the usefulness of being able to create functions inside such strings.

So this is basically my question - why use lambdas? Why are they included?

+1
python lambda
source share
1 answer

There is no deep answer to this. Once upon a time, someone contributed to the implementation of lambda code, and at a weak point ;-) Guido (van Rossum) applied the patch. That is all that is needed.

Sometimes it’s convenient, although it is mainly used excessively. For example, on various GUI systems, you often want to pass a simple callback function that will be called when an element in the graphical interface is clicked. lambda really good for this.

FYI, here is the Guido record made at the time, for the release of Python 1.0.0 (January 26, 1994). You can find this in the Python Misc/HISTORY distribution:

A new lambda keyword will appear. View expression

Lambda options: expression

gives an anonymous function. It really is just syntactic sugar; you can pinpoint a local function using

def some_temporary_name (parameters): return expression

Lambda expressions are especially useful in combination with map (), filter (), and reduce (), described below. Thanks to Amrit Prem for presenting this code (as well as map (), filter (), reduce () and xrange (!))

So blame Amrit Prem - LOL; -)

EDIT And click here to read a Guido blog post on this. Curiously, he did not remember to look into Misc/HISTORY , forgot the name of the author of the patch and that his memories were disabled for several years. Good thing I'm still there to cover it; -)

+9
source share

All Articles