help with map function

Duncan Booth duncan.booth at invalid.invalid
Fri Oct 22 04:07:01 EDT 2004


Michael wrote:

> In the book 'Text Processing Python,' they present a function that I'm
> having a real hard time understanding.
> 
> apply_each = lambda fns, args=[]: map(apply, fns, [args]*len(fns))
> 
A lambda creates an anonymous function. Assigning a lambda directly to a 
variable is simply an exercise in obfuscation. The same code can be more 
clearly expressed:

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


These days you can express the same thing more clearly with a list 
comprehension:

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

In general it would probably be better to define it as:

   def apply_each(fns, *args, **kw):
      return [ fn(*args, **kw) for fn in fns ]

although this changes slightly how you call it.

> 
> I understand that the lamda statement is passing a function that
> accepts a function and an iterable variable as arguments.
> 
> The function passed by lamda is a map statement that maps the function
> in the arguement list against each item in the iterable variable.
> 
> However, I don't understand what is happening in the 3rd arguement of
> map though.  What does [args]*len(fns) do?
> 
[args]*len(fns) is equivalent to [args, args, args, ...] where args is 
repeated as often as there are elements in the list. It means that every 
time apply is called it gets one of the functions and the args value as its 
parameters.






















More information about the Python-list mailing list