Compute the cumulative sum of a list until a zero appears
I have a (long) list in which zeros and ones appear at random: list_a = [1, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 1] I want to get the list_b sum of the list up to where 0 appears where 0 appears, retain 0 in the list list_b = [1, 2, 3, 0, 1, 2, 0, 1, 0, 1, 2, 3] I can implement this as follows: list_b = [] for i, x in enumerate(list_a): if x == 0: list_b.append(x) else: sum_value = 0 for j in list_a[i::-1]: if j != 0: sum_value += j else: break list_b.append(sum_value) print(list_b) but the actual list's length is very long. So, I want to improve code for high speed. (if it is not readable) I change