-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
  • 35,525
  • 9
  • 94
  • 135
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
  • 2,843
  • 1
  • 20
  • 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
  • 223,042
  • 33
  • 293
  • 407
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]))