For usual functions, you can annotate the type as follows
def my_function(arg1: int)
How do I do this in lambda?
lambda a: int, b: int : a+b
gives a syntax error.
A lambda function can have as many arguments as you need to use, but the body must be one single expression.
Lambda functions does not allow multiple statements, however, we can create two lambda functions and then call the other lambda function as a parameter to the first function.
Just like a normal function, a Lambda function can have multiple arguments with one expression. In Python, lambda expressions (or lambda forms) are utilized to construct anonymous functions. To do so, you will use the lambda keyword (just as you use def to define normal functions).
The question was: "How to specify argument type in python lambda?". Although the other answers are good, they do not provide answer to this main question.
The answer is: you cannot.
From the PEP specification of function annotations:
lambda 's syntax does not support annotations. The syntax of lambda could be changed to support annotations, by requiring parentheses around the parameter list. However it was decided [12] not to make this change because:
It would be an incompatible change. Lambda's are neutered anyway. The lambda can always be changed to a function.
For reference: https://stackoverflow.com/a/33833896/7051394
The problem is that reduce
will compute
result1 = func(x1, x2)
result2 = func(result1, x3)
...
your function accepts two lists
and returns a number, so on the second call the function fails (unless you only provide two elements).
To be able to use reduce
the function should accept two arguments and return a value of the same type of the arguments because the output of the function will be re-used as input at next iteration.
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