map

Chris Rebert clp2 at rebertia.com
Mon Aug 31 01:17:30 EDT 2009


On Sun, Aug 30, 2009 at 9:55 PM, elsa<kerensaelise at hotmail.com> wrote:
> Hi,
>
> 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?

Because myFunc is executed before map() is ever called, and you didn't
specify a value for the `a` parameter, hence you get an error about
not giving a value for `a`.
Another way of saying this: Python uses "eager evaluation"
(http://en.wikipedia.org/wiki/Eager_evaluation) most of the time.

> is there a way to make it work?

Use functools.partial to fill in the `b` parameter:
http://docs.python.org/library/functools.html#functools.partial

#untested example:
from functools import partial
f = partial(myFunc, b='booHoo')
map(f, myList)

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list