Home > Software engineering >  How can I add or subtract 3 items in a list based on a list of 2 operators in Python?
How can I add or subtract 3 items in a list based on a list of 2 operators in Python?

Time:03-04

Say I had a list number_list = [3,4,9]

And I wanted to operate on the numbers in the list based on a list such as operators = [' ', '-']

This program would take these lists and operate on the numbers using the list. Using the example lists, the following would be equated:

3   4 - 9

And the function would return the result of this equation.

Whilst I know the order for plus and minus operations does not matter, I plan on using this with multiplication and division as well, where order does matter.

Thank you to anyone who can provide some insight as to how I would do this.

CodePudding user response:

Lazy solution that does not care about security (read up on the "bad things" eval can do)

number_list = [3, 4, 9, 5]
operators = [" ", "-", '*']

# create a new list that can hold the above lists
new = [None] * (len(number_list)   len(operators))

# assign the first list using slice assignment
new[::2] = number_list
# assign the second list using slice assignment
new[1::2] = operators
# make all the elements to a string and eval
res = eval(''.join(map(str, new)))
print(res)

Output

-38

Assumption

operators must have valid operators and must be exactly one less than the size of number_list. Again, eval is not the way to go if you are doing this in actual production code.

  • Related