[SciPy-User] List of functions with different arguments

Warren Weckesser warren.weckesser@gmail....
Fri Mar 1 13:53:39 CST 2013

On Fri, Mar 1, 2013 at 2:24 PM, Per Nielsen <evilper@gmail.com> wrote:

> Hi all
> I apologize if this is too off topic, but I figured it was common in
> scientific computing.
> I am trying to make a list of copies of the same function, but with
> different extra input arguments. However, I am having problems getting the
> wanted output. I thought it was a problem with the way I refered to the
> function, but I tried a deepcopy and also the functions seem to have
> different ids.
> Here is my output from the attached script:
> simple
> [3, 3, 3]
> [4549677376, 4549677496, 4549677616]
> deepcopy
> [3, 3, 3]
> [4549677736, 4549677856, 4549677976]
> wanted/expected output: [1, 2, 3]
> Any help would be greatly appreciated :)
> Cheers,
> Per

The problem is this:

fct_list = [lambda x: fct(x, aa) for aa in range(1, 4)]

does not do what you want it to.  The use of `aa` in the lambda expression
is not replaced by the values of `aa` in the list comprehension.  Instead,
your lambdas will use whatever value the name 'aa' has when they are
called.  In this case, after the list comprehension is done, `aa` is 3, so
they always get a=3.  In fact, if immediately after you define `fct_list`
you do `del aa`, you'll get an error when you try to call fct_list[0](1).

One alternative is to import `partial` from `functools`:

from functools import partial
fct_list = [partial(fct, a=aa) for aa in range(1, 4)]


> _______________________________________________
> SciPy-User mailing list
> SciPy-User@scipy.org
> http://mail.scipy.org/mailman/listinfo/scipy-user
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/scipy-user/attachments/20130301/c9b7fc0e/attachment.html 

More information about the SciPy-User mailing list