from Hacker News

Python does support if-else in lambdas...

by globalrev on 11/10/08, 3:16 AM with 9 comments

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.

  • by kaens on 11/10/08, 4:16 AM

    That's the normal python idiom for the ternary operator in other languages if I'm not mistaken. Its lambdas are still crippled, for the same reasons people called them crippled before, which is fine for python, IMO.

    If I recall correctly, the if...else for ternary was added mainly because people were doing stuff with and...or to achieve the same effect.

  • by thomasmallen on 11/10/08, 4:46 AM

    * * disappears because those are for italizicing text here. Obviously they should really only be hidden if they're surrounding something.
  • by tzury on 11/10/08, 5:25 AM

    That's the way I write these if..else statements fib = lambda n: n in [0, 1] and n or fib(n-1) + fib(n - 2)