a = [5, 66, 7, 8, 9, ...]
Is it possible to make an iteration instead of writing like this?
a[1] - a[0] a[2] - a[1] a[3] - a[2] a[4] - a[3]
...
Thank you!
It's ok to use range
. However, programming (like maths) is about building on abstractions. Consecutive pairs [(x0, x1), (x1, x2), ..., (xn-2, xn-1)], are called pairwise combinations. See an example in the itertools docs. Once you have this function in your toolset, you can write:
for x, y in pairwise(xs): print(y - x)
Or used as a generator expression:
consecutive_diffs = (y - x for (x, y) in pairwise(xs))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With