Can someone give me a short explanation?

Peter Otten __peter__ at web.de
Mon Apr 5 05:20:20 EDT 2004


Senthoorkumaran Punniamoorthy wrote:

> I found this code in the book text processing with Python. But having
> little difficulty understanding how exactly it works and what should be
> passed as argument? Can someone decode this for me please?
> 
> apply_each = lambda fns, args=[]: map(apply, fns, [args]*len(fns))

This can be rewritten to (untested):

def apply_each(fns, args=[]):
    return map(apply, fns, [args]*len(fns))

Now we see that the intermediate list containing args len(fns) times, i. e.
once for every function passed in fns is superfluous:

def apply_each(fns, args=[])
   return map(lambda f: apply(f, args), fns)

or written in modern style:

def apply_each(fns, args=[]):
    return [f(*args) for f in fns]

It should be clear by now what this does: Call each function in the fns
sequence with the items in args as arguments, the default being no
arguments. Note that I find the list comprehension so readable that I'd be
tempted to put it literally into my code; so in a way we are back at the
beginning - only much better :-)

Peter





More information about the Python-list mailing list