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?
Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument. You give the function a value (argument) and then provide the operation (expression).
We use lambda functions when we require a nameless function for a short period of time. In Python, we generally use it as an argument to a higher-order function (a function that takes in other functions as arguments). Lambda functions are used along with built-in functions like filter() , map() etc.
The lambda keyword in Python provides a shortcut for declaring small anonymous functions. Lambda functions behave just like regular functions declared with the def keyword. They can be used whenever function objects are required.
Lambda functions are inline functions and thus execute comparatively faster.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With