This question already has an answer here:<ul><li> <a href="/questions/43101611/string-in-list-into-a-function" dir="ltr" rel="nofollow">String in list, into a function</a> <span class="question-originals-answer-count"> 5 answers </span> </li> </ul>
I imported myList from a .txt file (I converted the numbers to integers)
from math import * myList = [100, 'sin', 0, 1] x = pi
How would I go about calling the sin function for my given value of x?
I hoped this would simply return sin(pi), but it does not, because it is just the string 'sin(x)'Answer1:
Do not store functions as string literals, store the actual functions.
>>> from math import sin, exp, log >>> funcs = [sin, exp, log] >>> x = 0 >>> funcs(x) 0.0 >>> funcs(x) 1.0 >>> funcs(2.71) 0.9969486348916096
However, if you don't plan to do something more involved with that list of functions, you can just call them directly.