what is the difference for python between lambda and regular function?
Question:
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?
Answers:
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.).
lambda
creates an 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 map
and filter
. (look here)
You can pass normal functions to these functions too, but since mostly they are simple and they are not used anywhere else, it’s inconvenient to go through the 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]
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:
>>> def func(a, b):
return a * b
>>> func(2,3)
6
>>> type(func)
<class 'function'>
>>> func
<function func at 0x034B6E88>
Example of Lambda expression:
>>> multiply = lambda a, b: a * b
>>> multiply(2, 3)
6
>>> type(multiply)
<class 'function'>
>>> multiply
<function <lambda> at 0x034B6ED0>
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
def add(a,b):
return a+b
print(add(4,5))
Defining a lambda
add = lambda x, y : x + y
print(add(4,5))
Both lambda
and def
create the same kind of function – they have the same kind of metadata and capabilities. Their technical difference is syntactical:
- A
lambda
is an expression producing a function.
- A
def
is a statement producing a function.
This is everything that dictates how they can be used. Other apparent differences simply come from the information lambda
/def
can capture.
>>> def def_func(): pass
>>> lambda_func = lambda: None
>>> type(def_func) == type(lambda_func)
True
Usage: Expression vs. Statement
A lambda
is more flexible as expressions can be part of more language constructs.
# v--------------v arguments must be expressions
sort(values, key=lambda x: abs(x))
In contrast, a def
is more powerful as it can consist of more language constructs.
def encode(num, base):
while num: # statements must be inside statements
num, bit = divmod(num, base)
yield bit
These differences derive directly from one being an expression and the other being a statement. Python has no special rules to decide where a lambda
/def
may be used.
Where the wild <lambda>
s grow
The primary reason to assume lambda
and def
correspond to different kinds of function is metadata: lambda
is often referred to as an "anonymous function" and miraculously it always produces a function <lambda>
. Other quirks include "lambda functions can’t be pickled", and recently typing also does "not work" for lambda
.
That is because compared to def
syntax, the lambda
syntax has no way of specifying name, type annotations and similar. As such, Python simply fills in sane defaults for either: the name becomes <lambda>
and annotations are left empty.
>>> identity = lambda a: a
>>> identity.__qualname__
'<lambda>'
>>> identity.__annotations__
{}
Since <lambda>
is not a valid identifier, everything using this metadata to find the function – most prominently pickle
– fails.
However, that does not make the function an "anonymous function" type. The metadata can be patched up to insert what def
would provide:
>>> identity.__qualname__ = identity.__name__ = 'identity'
>>> identity
<function __main__.identity(a)>
Of course at that one point one can just use def
…
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?
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.).
lambda
creates an 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 map
and filter
. (look here)
You can pass normal functions to these functions too, but since mostly they are simple and they are not used anywhere else, it’s inconvenient to go through the 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]
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:
>>> def func(a, b):
return a * b
>>> func(2,3)
6
>>> type(func)
<class 'function'>
>>> func
<function func at 0x034B6E88>
Example of Lambda expression:
>>> multiply = lambda a, b: a * b
>>> multiply(2, 3)
6
>>> type(multiply)
<class 'function'>
>>> multiply
<function <lambda> at 0x034B6ED0>
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
def add(a,b):
return a+b
print(add(4,5))
Defining a lambda
add = lambda x, y : x + y
print(add(4,5))
Both lambda
and def
create the same kind of function – they have the same kind of metadata and capabilities. Their technical difference is syntactical:
- A
lambda
is an expression producing a function. - A
def
is a statement producing a function.
This is everything that dictates how they can be used. Other apparent differences simply come from the information lambda
/def
can capture.
>>> def def_func(): pass
>>> lambda_func = lambda: None
>>> type(def_func) == type(lambda_func)
True
Usage: Expression vs. Statement
A lambda
is more flexible as expressions can be part of more language constructs.
# v--------------v arguments must be expressions
sort(values, key=lambda x: abs(x))
In contrast, a def
is more powerful as it can consist of more language constructs.
def encode(num, base):
while num: # statements must be inside statements
num, bit = divmod(num, base)
yield bit
These differences derive directly from one being an expression and the other being a statement. Python has no special rules to decide where a lambda
/def
may be used.
Where the wild <lambda>
s grow
The primary reason to assume lambda
and def
correspond to different kinds of function is metadata: lambda
is often referred to as an "anonymous function" and miraculously it always produces a function <lambda>
. Other quirks include "lambda functions can’t be pickled", and recently typing also does "not work" for lambda
.
That is because compared to def
syntax, the lambda
syntax has no way of specifying name, type annotations and similar. As such, Python simply fills in sane defaults for either: the name becomes <lambda>
and annotations are left empty.
>>> identity = lambda a: a
>>> identity.__qualname__
'<lambda>'
>>> identity.__annotations__
{}
Since <lambda>
is not a valid identifier, everything using this metadata to find the function – most prominently pickle
– fails.
However, that does not make the function an "anonymous function" type. The metadata can be patched up to insert what def
would provide:
>>> identity.__qualname__ = identity.__name__ = 'identity'
>>> identity
<function __main__.identity(a)>
Of course at that one point one can just use def
…