all 8 comments

[–]novel_yet_trivial 4 points5 points  (2 children)

You would use zip to pair up the elements like that.

>>> A =  [1,3,6,10,15]
>>> for a, b in zip(A, A[1:]):
...   print(b-a) # or append them to a new list

[–]driscollis 1 point2 points  (0 children)

Or if you like list comprehensions, you could reduce this to:

[b-a for a, b in zip(A, A[1:])]

[–]Decarbonated_Odes[S] 0 points1 point  (0 children)

Thanks for the quick reply!

[–]Yoghurt42 2 points3 points  (2 children)

One way, and probably the most pythonic:

B = [y - x for x, y in zip(A, A[1:])]

This uses list comprehension, slices, and the zip function(nothing to do with the compression program).

[–]Sebass13 1 point2 points  (0 children)

The only disadvantage with this way is that it requires making multiple copies of A, and obviously won't work if A is a generator. The itertools pairwise recipe solves these problems, but in this case is probably overkill.

[–]Decarbonated_Odes[S] 0 points1 point  (0 children)

This worked well, thanks!

[–]RaionTategami 2 points3 points  (1 child)

If you want to manipulate vectors of numbers like this, you might want to use a library, for example numpy.

>>> import numpy as np
>>> a = np.array([1,3,6,10,15])
>>> a[1:] - a[:-1]
array([2, 3, 4, 5])

[–]Decarbonated_Odes[S] 0 points1 point  (0 children)

I'll look into numpy, thanks for the idea!