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?
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 likemap
andfilter
. ( 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 :
They are the same type so they are treated the same way:
Python also knows that
b
was defined as a lambda function and it sets that as function name: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.
Lambda is an inline function where we can do any functionality without a function name. It is helpful when we use it as an argument to a higher-order function. Eg: A function that takes in other functions as arguments.
Example of Function definition:
Example of Lambda expression:
Both returns same output value. Only object returned are different. "func" name for Function and for Lambda.
First consider the diff b/w the two.
Lambda functions: are operator can have any number of arguments, but it can have only one expression. It cannot contain any statements and it returns a function object which can be assigned to any variable. They can be used in the block they were created.
def functions: Functions help break our program into smaller and modular chunks. As our program grows larger and larger, functions make it more organised and manageable. They can be called and used anywhere we want.
Here you can get more clear difference by following example.
Defining a function
Defining a lambda
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 adef
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 defaultfunc_name
of"<lambda>"
. This may affect operation in esoteric cases - e.g. attempts to pickle functions.).