Ask Your Question

Apply a function to a list

asked 2011-12-11 09:53:07 -0500

sagefan gravatar image

Is there a simply syntax to apply a function like f(x) = x*exp(x) to a list of points L for example L=[1,2,3,4,19]. I want to be able to write something like f(L) which is a new list with the elements [f(1),f(2),f(3),f(4),f(19)]

edit retag flag offensive close merge delete

3 answers

Sort by ยป oldest newest most voted

answered 2011-12-11 10:11:41 -0500

benjaminfjones gravatar image

Use python's built-in map function:

f(x) = x*exp(x)
L = [1,2,3,4,19]
M = map(f, L)
edit flag offensive delete link more

answered 2011-12-14 02:30:57 -0500

niles gravatar image

If you want/need something fancier, you can use the @parallel decorator. When you decorate a function definition with this, it automatically becomes a function which can take a list (or other iterable) of inputs. The output in that case is an iterator which computes the values of the original function on each list element, and it does so in parallel. This is probably worse than map if your function calls are very very fast, but if the computation takes more time it's quite useful. And it has the advantage of requiring no extra syntax for the function call. The tradeoff is that the output list is not just the list of function values, but also contains the input values too, and thus requires some parsing. This is because the outputs are returned in the order that computations are finished, not the order they are begun.

There are some other answers on this site which expand on the (pretty weak) manual description of @parallel. Here's one to start with: When/How to use parallel.

edit flag offensive delete link more

answered 2011-12-11 20:29:10 -0500

Alternatively you can use the comprehension list syntax :

f(x) = x*exp(x)
L = [1,2,3,4,19]
M = [f(x) for x in L]

As far as I know, this is a syntactic sugar for the map function proposed by benjaminfjones

edit flag offensive delete link more



It's close. There's one unexpected scoping consequence, though-- after running the above code, the variable x is now equal to 19, not the usual var("x"). list(f(x) for x in L) doesn't have this problem.

DSM gravatar imageDSM ( 2011-12-14 03:14:59 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools


Asked: 2011-12-11 09:53:07 -0500

Seen: 1,377 times

Last updated: Dec 14 '11