Executing a list of functions
HMS Surprise
john at datavoiceint.com
Mon Mar 19 15:59:06 CET 2007
On Mar 16, 6:44 pm, James Stroud <jstr... at mbi.ucla.edu> wrote:
> HMS Surprise wrote:
> > Seems to me that one should be able to put the names of several
> > functions in a list and then have the list executed. But it seems the
> > output of the functions is hidden, only their return value is visible.
> > Is this because the list execution is another scope?
>
> > Thanx,
>
> > jh
>
> > ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
>
> > def a():
> > print "this is a"
>
> > def b():
> > print "this is b"
>
> > lst = [a(), b()]
>
> > lst
>
> The "print" statement does nothing to return a value from the function,
> so the strings "this is *" will not be stored in your list. They will,
> however, be printed if you are some how observing your program output
> (e.g. running it in IDLE, or a command shell).
>
> To save the "results" of the functions, you need to produce results,
> which means actually using "return" to return some value. Here is an
> example:
>
> def a():
> print "this is a"
> return "return value from a"
>
> def b():
> print "this is b"
> return "return value from b"
>
> functions = [a, b]
> results = [f() for f in functions]
> print results
>
> Here is the result of this example:
>
> py> def a():
> ... print "this is a"
> ... return "return value from a"
> ...
> py> def b():
> ... print "this is b"
> ... return "return value from b"
> ...
> py> functions = [a, b]
> py> results = [f() for f in functions]
> this is a
> this is b
> py> print results
> ['return value from a', 'return value from b']
>
> A fun, but unfortunately deprecated, way to do this is with the "apply"
> function in conjunction with the "map" function:
>
> def a():
> print "this is a"
> return "return value from a"
>
> def b():
> print "this is b"
> return "return value from b"
>
> functions = [a, b]
> results = map(apply, functions)
> print results
>
> Here is this example at work:
>
> py> def a():
> ... print "this is a"
> ... return "return value from a"
> ...
> py> def b():
> ... print "this is b"
> ... return "return value from b"
> ...
> py> functions = [a, b]
> py> results = map(apply, functions)
> this is a
> this is b
> py> print results
> ['return value from a', 'return value from b']
>
> James
Thanks to all for posting.
Why is apply deprecated?
jh
More information about the Python-list
mailing list