Example of how to apply a function to a list in python:
Apply a function to a list in python using map()
Let's create a list of angles in degrees
mylist = [0,25,45,75,90]
and a function that calculate cos(angle):
import mathdef myfunction(angle):angle_in_radian = math.radians(angle)return math.cos(angle_in_radian)
To apply the function for each items in the list, a solution is to use the python built-in function map() :
list( map(myfunction, mylist) )
gives here
[1.0, 0.9063077870366499, 0.7071067811865476, 0.25881904510252074, 6.123233995736766e-17]
Apply a function to a list in python using numpy
Another possible solution is to convert the list into an array:
import numpy as npmylist = [0,25,45,75,90]A = np.array(mylist)def myfunction(angle):angle_in_radian = np.radians(angle)return np.cos(angle_in_radian)print( list( myfunction(A) ) )
gives
[1.0, 0.9063077870366499, 0.7071067811865476, 0.25881904510252074, 6.123233995736766e-17]
