Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: evaluating a function with the argument taking multiple values

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

like image 789
Kim Avatar asked Jun 04 '26 16:06

Kim


1 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)).

like image 155
Cut7er Avatar answered Jun 06 '26 05:06

Cut7er