Python: evaluating a function with the argument taking multiple values

Viewed 1186

Asssume I have a function in python which returns the power of 2 of its input

def f(x):
    return x**2

Assume also I have a vector of integers 1,2,3,4,5

I = asarray(list(range(1,6)))

Now I want to evaluate the function f with all inputs from I and the results should be in a vector of dimensions 5 (A 1x5 array in Python). My desired result is then: [1,4,9,16,25].

Can I get this result WITHOUT the use of a for or any other loop?

I have used array package

2 Answers

directly from the pythontips website...

use the map function!

squared = list(map(lambda x: x**2, I))

if you want to use your function inside the map-function, just do squared = list(map(f, I)).

There are generally two classical ways to apply a function to all elements of an iterable and store the results in a list. The more flexible one is a list comprehension:

result = [f(x) for x in range(1, 6)]  # the upper bound is exclusive!

The other option is map which allows a more concise notation, in particular if you have a named function available and do not need to use a lambda or the like:

result = map(f, range(1, 6))        # Python2: returns list
result = list(map(f, range(1, 6)))  # Python3: return iterator, so cast
Related