rurpy at rurpy at
Mon Aug 31 07:19:13 CEST 2009

On 08/30/2009 10:55 PM, elsa wrote:
> i have a question about the built in map function. Here 'tis:
> say I have a list, myList. Now say I have a function with more than
> one argument:
> myFunc(a, b='None')
> now, say I want to map myFunc onto myList, with always the same
> argument for b, but iterating over a:
> map(myFunc(b='booHoo'), myList)
> Why doesn't this work? is there a way to make it work?

When you write "map(myFunc(b='booHoo'), myList)", you are telling
Python to call myFunc before the map function is called, because
an argument list, "(b='booHoo')", follows myFunc.  You want
to pass map a function object, not the results of calling a
function object.

A couple ways to do what you want:

  map(lambda a: myFunc(a, b='booHoo'), myList)

The lamba expression creates a new function of one argument
(which is needed by map) that, when executed, will call myFunc
with the two arguments it needs.

You can also just define an ordinary function that does
the same thing as the lambda above:

  def tmpFunc (a)
    myFunc (a, b='booHoo')
  map (tmpFunc, myList)

In the functools module there is a function called "partial"
that does something similar to the lambda above.  I'll leave
it to you you look it up if interested.


More information about the Python-list mailing list