pythonlistmath

How do i calculate a math problem from a list in python?


I have a list in python that looks something like this:

list = [5, "-", 4, "*", 8]

I would like to calculate the math problem in the list so:

answer = 5 - 4 * 8

So the variable "answer" is -27.


Solution

  • This will work:

    eval(''.join([str(x) for x in list]))
    

    But be careful using eval!