python – can lambda have more than one return

Question:

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
Asked By: Shengjie

||

Answers:

Sure:

lambda a, b: (a + 1, b * 1)
Answered By: Daniel Roseman

what about:

lambda a,b: (a+1,b*1)
Answered By: mgilson

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
Answered By: Óscar López

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)]
Answered By: Rajesh
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.