# Apply a function to a list

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 close merge delete

Sort by » oldest newest most voted

Use python's built-in map function:

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

more

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

more

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.

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.

more