Conditional statement in a one line lambda function in python?

Nathan Bush picture Nathan Bush · Apr 2, 2013 · Viewed 129.2k times · Source

Apologies if this has been asked before, but I couldn't see it anywhere.

Essentially I've come across a scenario where i need to make use of an if statement inside a lambda function. What makes it difficult is that ideally it needs to be in a single line of code (if thats even possible?)

Normally, i would write this:

T = 250

if (T > 200):
    rate = 200*exp(-T)
else:
    rate = 400*exp(-T)

return (rate)

However i need it to look like this:

rate = lambda(T) : if (T>200): return(200*exp(-T)); else: return(400*exp(-T))

I realize the easier thing to do would to take the decision making outside of the lambda functions, and then have a separate lambda function for each case, but its not really suitable here. The lambda functions are stored in an array and accessed when needed, with each array element corresponding to a particular "rate" so having two separate rows for the same "rate" would mess things up. Any help would be greatly appreciated, or if its not possible, some confirmation from others would be nice :)

Answer

shx2 picture shx2 · Apr 2, 2013

Use the exp1 if cond else exp2 syntax.

rate = lambda T: 200*exp(-T) if T>200 else 400*exp(-T)

Note you don't use return in lambda expressions.