Advertisements

I’m stuck on a iteration problem.

I have a list of numbers, like: list = [100, 70, 25, 10, 5].

I would like to iterate over the list and generate a new array, such that each "result" becomes the new number from which the next is subtracted:

100-70 = 30

30 (result) – 25 = 5

5 (result) – 10 = -5

-5 (result) – 5 = -10

(I think you get the idea)

new_array = [30, 5, -5, -10]

I am not able to arrive at the solution with Numpy.

Any help is appreciated!

Thank you!

### >Solution :

You can use the subtract ufunc with numpy.ufunc.accumulate.

```
numbers = [100, 70, 25, 10, 5]
result = np.subtract.accumulate(numbers)[1:]
print(result)
```

Output:

```
[ 30 5 -5 -10]
```