Python does support if-else in lambdas...
Just learned some tricks in #python in IRC-freenode:
I have heard a lot of complaints about Pythons lambdas being crippled but Python does allow if-else in lambdas, I didn't know before. Not in the ordinary Python way but:
f = lambda n_: (lambda ns: ns.__setitem__('f', lambda n: n if n in [0, 1] else \ fib(n-1) + fib(n - 2)) or ns['f'](n_))({})
map(lambda n: n3 if n % 2 == 1 else n2, range(10))
>>> reduce(lambda x,y: x+y if y % 2 == 1 else x-y, [1,2,3,4,5]) 3
>>> fib = lambda n: n if n in [0, 1] else fib(n-1) + fib(n - 2) >>> fib(12) 144
also: [n3 if n%2 else n2 for n in range(10)]
For soem reason * * disappears if next to each other.
9 comments
[ 3.4 ms ] story [ 34.3 ms ] threadIf I recall correctly, the if...else for ternary was added mainly because people were doing stuff with and...or to achieve the same effect.
I have felt a need for it sometimes though. Very complicated lambdas are perhaps generally better off as normal functions.
But I hate creating one-time-use functions if it isn't necessary.