why - what is the difference for python between lambda and regular function?
why use lambda functions (2)
lambda create anonymous function. This idea has been taken from functional programming languages. In this way you can create and pass the function to other functions like
filter. ( look here )
You can pass normal functions to these functions too, but since mostly their simple and they have used nowhere else, it's inconvenient to through to whole process of definfing a new function.
As an example take a look at this :
>>> a = [1, 2, 3, 4] >>> print map( lambda x : x*2 + 1, a ) [3, 5, 7, 9, 11]
I'm curious about the difference between
lambda function and a regular function (defined with
def) - in the python level. (I know what is the difference for programmers and when to use each one.)
>>> def a(): return 1 >>> b = lambda: 1 >>> a <function a at 0x0000000004036F98> >>> b <function <lambda> at 0x0000000004031588>
As we can see - python knows that
b is a
lambda function and
a is a regular function. why is that? what is the difference between them to python?
The only difference is that (a) the body of a lambda can consist of only a single expression, the result of which is returned from the function created and (b) a
lambda expression is an expression which evaluates to a function object, while a
def statement has no value, and creates a function object and binds it to a name.
In all other material respects they result in identical objects - the same scope and capture rules apply. (Immaterial differences are that
lambda-created functions have a default
"<lambda>". This may affect operation in esoteric cases - e.g. attempts to pickle functions.).