Lambdaizing Python Code

Fernando Pérez fperez528 at
Sun Sep 29 03:15:38 CEST 2002

Terry Hancock wrote:

> Not that I want to sign up for the style police or
> anything, but ...
> Would respectfully like to point out that this could
> as well be represented:
> def plur(word, number):
>     if number > 1:
>         word = word + 's'
>     return '%d %s' % (number, word)

Well, not quite. You need 'if number !=1'. Otherwise this happens:
In [36]: plur('cat',0)
Out[36]: '0 cat'

when you want:

In [37]: plur0('cat',0)
Out[37]: '0 cats'

Anyway, I know that the above is equivalent to my lambda. I just like and 
often use lambda for quick, simple one-liners. The page originally referred 
to by the OP is a nightmare, and a funny example of abusing the lambda idea 
to death. But I don't mind them in simple cases, nor do I  find them 
particularly unreadable.

My original:

plur=lambda s,n:'%s %s' % (n,s+('','s')[n!=1])

is fine for me. I see exactly what it does in one pass of my eyes. That's why 
_I_ like lambdas, and where I use them. But this is absolutely a matter of 
_personal_ preference.

I'm a big defender of code clarity and readability over conciseness/cleverness 
(I'm an ex-perler, for good reason). It's just that in cases like the above, 
_I_ find the lambda form quicker to visualize mentally and overall simpler to 
my taste. Feel free to differ.



More information about the Python-list mailing list