Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - can lambda have more than one return

I know lambda doesn't have a return expression. Normally

def one_return(a):     #logic is here     c = a + 1     return c 

can be written:

lambda a : a + 1 

How about write this one in a lambda function:

def two_returns(a, b):     # logic is here     c = a + 1     d = b * 1     return c, d 
like image 734
Shengjie Avatar asked May 21 '13 15:05

Shengjie


People also ask

Can lambda function return more than one value?

The characteristics of lambda functions are:Lambda functions are syntactically restricted to return a single expression. You can use them as an anonymous function inside other functions. The lambda functions do not need a return statement, they always return a single expression.

Can Python lambda have multiple statements?

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.

Can you have multiple returns in Python?

Python functions can return multiple values. These values can be stored in variables directly. A function is not restricted to return a variable, it can return zero, one, two or more values.

Can a lambda have two triggers?

Your function can have multiple triggers. Each trigger acts as a client invoking your function independently. Each event that Lambda passes to your function has data from only one client or trigger.


2 Answers

Yes, it's possible. Because an expression such as this at the end of a function:

return a, b 

Is equivalent to this:

return (a, b) 

And there, you're really returning a single value: a tuple which happens to have two elements. So it's ok to have a lambda return a tuple, because it's a single value:

lambda a, b: (a, b) # here the return is implicit 
like image 134
Óscar López Avatar answered Oct 13 '22 06:10

Óscar López


Sure:

lambda a, b: (a + 1, b * 1) 
like image 44
Daniel Roseman Avatar answered Oct 13 '22 08:10

Daniel Roseman