python - can lambda have more than one return
Asked Answered
B

4

42

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
Bashemath answered 21/5, 2013 at 15:39 Comment(6)
That's not more than one return, it's not even a single return with multiple values. It's one return with one value (which happens to be a tuple).Bis
+1 @delnan's comment, this is a major reason I dislike Python's promotion of , to tuple all over the place. It obfuscates what's actually going on.Homopolar
@Homopolar What? , is not "promoted to tuple", that's literally the syntax for tuple creation. And it's perfectly clear IMHO.Bis
@delnan I mean, excluding the parens. It's not obvious all the time, when they're excluded.Homopolar
@Homopolar Can you give an example where it is not obvious?Callahan
@lzkata: who gave you the idea that tuples should have parens? The parens are only for operator precedence purposesOxa
D
57

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
Dissension answered 21/5, 2013 at 15:43 Comment(1)
in other words, it's a precedence issue. , has lower precedence than lambdaOxa
S
18

Sure:

lambda a, b: (a + 1, b * 1)
Scuta answered 21/5, 2013 at 15:40 Comment(0)
S
11

what about:

lambda a,b: (a+1,b*1)
Slushy answered 21/5, 2013 at 15:41 Comment(0)
R
1

Print the table of 2 and 3 with a single range iteration.

>>> list(map(lambda n: n*2, range(1,11)))
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]


>>> list(map(lambda n: (n*2, n*3) , range(1,11)))
[(2, 3), (4, 6), (6, 9), (8, 12), (10, 15), (12, 18), (14, 21), (16, 24), (18, 27), (20, 30)]
Rysler answered 8/1, 2021 at 6:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.