I was wondering if it was possible to calculate a list, for example this one
calculation = [1, "+", 2, "*", 15]
so it returns 31.
I was wondering if it was possible to calculate a list, for example this one
calculation = [1, "+", 2, "*", 15]
so it returns 31.
Don't use eval
ever. Check this post
Instead you can refer some other library like asteval
from asteval import Interpreter
aeval = Interpreter()
calculation = [1, "+", 2, "*", 15]
aeval.eval(''.join(map(str, calculation)))
Sure:
eval(' '.join(map(str, calculation)), {}, {})
The inner join
(no pun intended) builds a single string which is valid Python code, then you simply eval()
it.
The two {}
s are optional, they make it so the code runs without access to the surrounding global and local variables.
eval
can be used for evaluating an expression (which is in the form of a string) in python.
Desired output can be obtained as below
eval(''.join([str(x) for x in calculation]))