Question
In the context of this exercise, how might the example lambda functions be rewritten using the regular form, utilizing def
?
Answer
Lambda functions can usually always be written in the normal Python function structure. This post will try to rewrite the example lambda functions in the normal Python function structure, which utilizes def
and consists of multiple lines, as opposed to lambda functions which are always a single line.
For the first lambda function
mylambda = lambda x: (x * 2) + 3
Rewriting this using the def
structure could be as follows:
def my_function(x):
return (x * 2) + 3
For the second example lambda function
stringlambda = lambda x: x.lower()
We can rewrite this like:
def string_function(x):
return x.lower()
If we generalize how this is done, basically, the parameters of the function are the parameters that follow right after the keyword lambda
and before the colon :
. For example, for this lambda, the parameters are x
and y
sumlambda = lambda x, y: x + y
The returned value of the function is just what follows the colon :
,
x + y
.
Written using the normal structure, this would be
def sum_function(x, y):
return x + y