Lambdaizing Python Code

Terry Hancock hancock at
Thu Sep 26 16:02:01 EDT 2002

From: gerson.kurz at (Gerson Kurz)
> A really usefull study ... NOT. 
> also known as "making Guido regret he put lambda in THE BEST

That was scary. ;-D

Paraphrasing "Ghostbusters" --
"Okay, guys, important safety tip: avoid lambda."

From: Fernando Pérez <fperez528 at>
> Why not just a simple function?
> In [23]: plur=lambda s,n:'%s %s' % (n,s+('','s')[n!=1])
> In [24]: plur('cat',0)
> Out[24]: '0 cats'
> In [25]: plur('cat',1)
> Out[25]: '1 cat'
> In [26]: plur('cat',9)
> Out[26]: '9 cats'
> In [27]: na=1; np=3; nl=1; ng=0
> In [28]: print "Found %s, %s, %s, %s" % (plur('apple',na),plur('plum',np),
>    ....: plur('lemon',nl),plur('grape',ng))
> Found 1 apple, 3 plums, 1 lemon, 0 grapes
> If the list is big the above can easily be automated with a map or a list 
> comprehension.

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)

and would, IMHO, be much more obvious in function to
the reader.  Nothing says you have to use "lambda"
just because you might use a map or list comprehension.

IMHO, if you need to assign lambda to a variable,
you probably want to use a named function anyway. 
(Basically, it's semantically identical to do so,
(I think) -- except that you remove the expression
limitation, which makes for more intuitive code.

It occurs to me that the plur() function is a very
good idea, especially since it is possibly
multi-lingual (e.g. in Russian, Swahili, and Japanese
the pluralization rules are completely different --
Russian typically inflects with an "i" ending, Swahili
uses prefixes (e.g. "mtoto" / "watoto"). Japanese is
potentially more challenging, as the word remains
unchanged, but the number acquires a counter
"empitsu sambon" (and they're normally separated in
the sentence (e.g. "empitsu ga sambon aru" = "there
are three pencils").  I wonder if there are any
other challenge cases to consider, and whether a
more general pluralization scheme is possible.

PUB ( has a problem
with this, in that much of the pluralization code is
mixed in, and assumes English (or other languages where
you can make a plural by adding "s").

Mind you, even in english the plur() function will
break down for sheep, tooth, calf, and a host of
other exception words.

Fun concept.


Terry Hancock
hancock at       
Anansi Spaceworks         
P.O. Box 60583                     
Pasadena, CA 91116-6583

More information about the Python-list mailing list