Following W3schools explanation , lambda functions are anonymous functions that can be used inside other functions. I think I do not fully understand its usefulness and use despite the many examples on the page.
Here are my doubts:
In the following example, where is the value of the variable a declared?
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
If
mytripler()
it is the lambda it no longer seems so anonymous to me.
Why use lambda if you can do the following?
def myfunc(a, n):
return a * n
print(myfunc(3, 11))
When you say that they are anonymous functions, do you mean that they are functions that don't have a name by which to call their execution like this MiFuncion()
?
The W3Schools example is a case of currying . Certainly you can achieve the same output doing it the way you propose, but what (I suppose) the first example wants to demonstrate is the possibility of applying functional programming techniques in Python.
For the latter it
lambda
helps quite a bit, since it may be unnecessary to define a regular function (usingdef
it and giving it a name), when our goal is to obtain things such as closures or currying .Let's take an example to see this better, since certainly the W3Schools example says a lot and a little at the same time.
Imagine that you have a program where there is a class
Person
, which has an attributeage
, and you are constantly filtering people objects according to their ages. You could have a function that implements currying and that allows you (at least) the following three benefits:The implementation would look like this:
As you can see, the use of
lambda
made the implementation much more direct. Thanks to this we didn't have the need to define a separate function whose only intention is to be returned to allow currying .Of course we could have implemented the code above with an Object Oriented paradigm, having a parent class
Filtro
with the methodfiltrar()
, which serves as an interface, and have child classes that specialize and override that method according to each case.It is valid? Of course, but the implementation used the functional paradigm is too. Therein, in my opinion, lies the beauty of this language: in the flexibility it provides.
Another common use of
lambda
In my experience, where I have seen the most use of anonymous functions is when providing callables (or callables) for the parameter
key
of built- in ordering functions. For example:There is a clear advantage of having
lambda
, being able to define and use a function right where it is needed.Be careful, in this case I prefer the use of
operators.attrgetter
, but the use of is equallylambda
widespread for this purpose.What is?
In Python,
lambda
it is a way to define anonymous functions, they receive and return parametersIt has the following syntax
examples
In the following example, we can return a number multiplied with another with a function
lambda
The above example is equivalent to defining a function as follows
But, there are specific cases where we can return a function
In this case it
multiplyNumb
returns a function , so we could do the followingIn this case, we have a function stored in
firstNumb
, since the main function returns a lambda function , the value offirstNuumb
will beThe 2 because we gave the first function "2" as a parameter, so
n
it is replaced with 2Then, we only have to call the function to define the value of
a
To define it we simply call the function again, knowing that it will receive a parameter which will be the value of
a
The result will finally be 40, because we have called the lambda function and we have given it 20 so that it interprets it with the value of
a
, then it returns the 2 that we had multiplied with the parameter that we gave itWhy use
lambda
?There are specific cases in which we have to return a function, if this is not your case, the example you gave would suffice
But, if we have to return a function specifically, we use
lambda
Result
They are said to be anonymous functions because they do not have a name to be called by, they are returned by a function or assigned to a variable.
In the example above, a function is defined
lambda
and called, if it is not given a name, it cannot be calledThen we define the function like this
And we add parentheses to call the function
It will return
25
, since we are calling the function passing me "5" as a parameterLambda functions are not a concept unique to Python. They are typical of functional programming , where it is common for you to pass functions as parameters to other functions, or to return a function as the result of calling another function.
Although the concept of returning a function is strange, and its fields of application could be considered "advanced" (decorators, closures, even the possibility of completely avoiding OOP and allowing to maintain state in function variables instead of in object attributes ), the concept of passing a function as a parameter is easier to understand.
For example, imagine that you want to make a function that times how long it takes to execute another function that receives it as a parameter (and for simplicity we will assume that the function it receives as a parameter has no parameters). So it would be something like this:
We can now use it to time any "normal" named function, such as:
Notice a very important detail . To the function
cronometra()
we are passing the name of the function to time. A typical mistake would be to writecronometra(sumar_100_numeros())
. This would be wrong because in this case we would be callingsumar_100_numeros()
before , to then pass the result tocronometra()
. This would give an error, since that result would be an integer, and not a function, so when youcronometra
try to callfuncion_a_cronometrar()
it it would break, since an integer cannot be called.In functional programming it is common to pass functions as parameters of other functions. In the Python standard library itself you have the functions
sorted()
,max()
ormin()
that admit a parameter calledkey
which would be the function that should be used on each element of the list to sort, before sorting it. Internally itsorted()
will call that function for each item in the list, and use the result of that call to compare the items to each other.This allows us, for example, to order a list of tuples by their second element:
Result:
So far we have talked about functions as parameters and lambdas have not appeared anywhere. When is a lambda useful?
The answer is: when the function that I am going to define is not usable in any other part of the code, and I only define it for that particular case.
In this case, the function does not need a name because it will be received as a parameter, and the parameter already has a name (for example
key
, in the case ofsorted()
, orfuncion_a_cronometrar
in our first example). It is through the name of the parameter that we will invoke the function. His "real" name is irrelevant.In that case I can use a lambda function. However in Python lambda functions are quite special. In any other language, a lambda could have conditionals, loops, etc... Their only characteristic would be that they have no name, and that they are assigned to a parameter (or returned as a result). On the other hand, in python it is not possible to write the function code in the place where the parameter would go because python does not have curly braces , and therefore we cannot use "inline" control structures. Therefore, python lambdas are very limited and can only be an expression.
would be equivalent to the function
So we could rewrite our sort example with a lambda like this:
Another usage example
Another example would be to perform partial padding of parameters, which will be understood with the first example that I put before, that of the function that timed another function.
In that example, the function
cronometra()
is limited to callingfuncion_a_cronometrar()
without arguments, which was good for timingsumar_100_numeros
, but what if I want to time, without changing the functioncronometra()
, a function that receives parameters, such as:In this case I can't do
cronometra(sumar_m_numeros)
it because I wouldn't be passing any parameter and it would give an error, but I can't eithercronometra(sumar_m_numeros(1000))
, because in this case I would call the function first and pass the result tocronometra()
, instead of passing the function to it.The solution would be to create a "dumb" function that takes no parameters and internally calls
sumar_m_numeros(1000)
, and pass that "dumb" function tocronometra()
.Change "dumb" to lambda and we're done:
Stop to think about this example for a moment. What we're passing to
cronometra()
is not the result of executesumar_m_numeros(1000)
, but a function (the lambda) that hasn't been executed yet. Whencronometra()
you invokefuncion_a_cronometrar()
it, it will be calling the lambda, and at that moment, when executing the lambda, the expression will be evaluated,sumar_m_numeros(1000)
calling this function for the first time.This pattern is often seen when we need to pass another function that doesn't receive parameters to a function, but want to execute one that does. A typical place you see this is when binding actions to buttons in a GUI like Tkinter.