-1

I was wondering if it was possible to calculate a list, for example this one

calculation = [1, "+", 2, "*", 15]

so it returns 31.

Aran-Fey
  • 39,665
  • 11
  • 104
  • 149
Luca Roth
  • 3
  • 1

4 Answers4

2

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)))
Vishvajit Pathak
  • 3,351
  • 1
  • 21
  • 16
0

Maybe you could take a look at a binary expression tree.

binary expression tree

0

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.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

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]))