def bar(x):
# some expensive calculation
<snip>
foo = lambda(x): bar(x) if bar(x) > 10 else 0
However here I have calculated foo twice. Is there a way to still write this as a one liner but avoid the double evaluation. I tried
foo = lambda(x): v if (v = bar(x)) > 10 else 0
but that doesn't work.
Preevaluate:
foo = lambda(x): x if x > 10 else 0
result = foo(bar(x))
Here you can see what is the similarities to your code:
lambda (x): foo(x) if foo(x) > 10 else 0 == (lambda(x): x if x > 10 else 0)(foo(x))
What you seek is not possible unless you create some kind of mutable state object or some other weird trick.
@Alakazam answer is tricky and smart, use it on your own risk. It can be better using iterators and next
to avoid extra intermediate list:
lambda x: next(res if res > 10 else 0 for res in (bar(x), ))
Here you have the live example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With