Ask Your Question
3

Apply a function to a list

asked 2011-12-11 16:53:07 +0100

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
3

answered 2011-12-11 17:11:41 +0100

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
4

answered 2011-12-12 03:29:10 +0100

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

Comments

1

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 10:14:59 +0100 )edit
3

answered 2011-12-14 09:30:57 +0100

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

Your Answer

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

Add Answer

Question Tools

Stats

Asked: 2011-12-11 16:53:07 +0100

Seen: 5,837 times

Last updated: Dec 14 '11