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
6
  • 13
    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). Commented May 21, 2013 at 16:00
  • 2
    +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. Commented May 21, 2013 at 18:22
  • 6
    @Izkata What? , is not "promoted to tuple", that's literally the syntax for tuple creation. And it's perfectly clear IMHO. Commented May 21, 2013 at 18:25
  • 2
    @delnan I mean, excluding the parens. It's not obvious all the time, when they're excluded. Commented May 21, 2013 at 18:53
  • 2
    @lzkata: who gave you the idea that tuples should have parens? The parens are only for operator precedence purposes Commented May 21, 2013 at 19:49

5 Answers 5

58

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
Sign up to request clarification or add additional context in comments.

1 Comment

in other words, it's a precedence issue. , has lower precedence than lambda
18

Sure:

lambda a, b: (a + 1, b * 1)

Comments

11

what about:

lambda a,b: (a+1,b*1)

Comments

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)]

Comments

0

not sure if what worked for me is a good practice, but I needed a conditional lambda, which worked this way:

  • If variable A is 'Not A', I want to set variable A to 'A' and variable B to 'B'

  • else (if variable A is 'A'), I want to set variable A to 'Not A' and variable B to 'Not B'

lambda: (variable_a='A', variable_b='B') if variable_a=='Not A' else (variable_a='Not A', variable_b='Not B')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.