Sum numbers in a list but change their sign after zero is encountered

Here's a solution that cycles between two operators (addition and subtraction) whenever a value in the list is zero:

from operator import add, sub
from itertools import cycle

cycler = cycle([add, sub])
current_operator = next(cycler)

result = 0
my_list = [1, 2, 0, 3, 0, 4]

for number in my_list:
    if number == 0:
        current_op = next(cycler)
    else:
        result = current_operator(result, number)

Change the sign when the element of the list is equal 0.

result = 0
current_sign = 1
for element in your_list:
    if element == 0:
       current_sign *= -1
    result += current_sign*element

Tags:

Python

List

Sum