[Tutor] Why use lambda?

Alan Gauld alan.gauld at btinternet.com
Sun Aug 3 01:28:11 CEST 2008

"bob gailer" <bgailer at gmail.com> wrote

> In my Python Pipelines program for the Count stage I have:
> opts = {
>  'characters' : lambda rec, tot: tot + len(rec),
>  'words' :      lambda rec, tot: tot + len(rec.split()),
>  'lines' :      lambda rec, tot: tot + 1,
>  'minline' :    lambda rec, tot: min(len(rec), tot),
>  'maxline' :    lambda rec, tot: max(len(rec), tot),
>       }

def characters(rec,tot): return tot + len(rec)
def words(rec,tot): return tot + len(rec.split())

Not many more characters than using lambda and
avoids the need for the dictionary lookup:

instead of

w = opts['words'](r,c)

just use:

w = words(r,c)

If you need the dictionary for dynamic lookup then just insert
the functions intop the dict:

opts = {
'characters' : characters,
'worsds' : words,

> Consider how many more lines of code it would take if I had to use 
> defs.

More or less by definition a Python lambda expression can
be replaced with a one-liner function.

> Consider how readable it is to have the expressions all in one 
> place.

In this case I'm not sure the gain is huge, its largely a matter of
personal preference.

Alan G. 

More information about the Tutor mailing list