Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading