I understand what they do and how to use them, but I'm still somewhat confused as to why they're included in Python. What benefit is there in using them, over the normal function definition style?
The only real difference that I can think of is that you can create them inside an expression. For example, if myList was a list of ints and you wanted to add one to every element, you could use
list(map(lambda x: x+1, myList))
Whereas if you wanted to do that with function definitions, you'd have to define it elsewhere and then pass that variable.
However, I seriously doubt that this relatively minor convenience would justify their inclusion in the language, so I'm guessing there's something I'm missing. Or, perhaps, I'm underestimating the usefulness of being able to create functions inside lines like that.
So, that's basically my question - what are lambdas supposed to be used for? Why are they included?
There isn't a deep answer to this. A long time ago, someone contributed the code to implement lambda
, and in a weak moment ;-) Guido (van Rossum) applied the patch. That's all there is to it.
It is handy sometimes, although it's mostly over-used. For example, in various GUI systems you often want to pass a simple callback function to be triggered when some element in the GUI is clicked. lambda
s are really nice for that.
FYI, here's the entry Guido made at the time, for Python release 1.0.0 (26 January 1994). You can find this in a Python distribution's Misc/HISTORY
file:
There is a new keyword 'lambda'. An expression of the form
lambda parameters : expression
yields an anonymous function. This is really only syntactic sugar;
you can just as well define a local function using
def some_temporary_name(parameters): return expression
Lambda expressions are particularly useful in combination with map(),
filter() and reduce(), described below. Thanks to Amrit Prem for
submitting this code (as well as map(), filter(), reduce() and
xrange())!
So blame Amrit Prem - LOL ;-)
EDIT And click here to read Guido's blog post on the subject. It's curious that he didn't remember to look in Misc/HISTORY
, forgot the name of the patch author, and that his memories are off by several years. Good thing I'm still around to cover for him ;-)