z[1:] -= z[:-1].copy()
Short and sweet, with no slow Python loops. We take views of all but the first element (z[1:]
) and all but the last (z[:-1]
), and subtract elementwise. The copy makes sure we subtract the original element values instead of the values we’re computing. (On NumPy 1.13 and up, you can skip the copy
call.)