what is the difference for python between lambda and regular function?

They are the same type so they are treated the same way:

>>> type(a)
<type 'function'>
>>> type(b)
<type 'function'>

Python also knows that b was defined as a lambda function and it sets that as function name:

>>> a.func_name
'a'
>>> b.func_name
'<lambda>'

In other words, it influences the name that the function will get but as far as Python is concerned, both are functions which means they can be mostly used in the same way. See mgilson's comment below for an important difference between functions and lambda functions regarding pickling.


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 func_name of "<lambda>". This may affect operation in esoteric cases - e.g. attempts to pickle functions.).

Tags:

Python

Lambda