I am creating a program in python that, given a list, will find the difference between a number in the list and the number following it.
For example,
lst = [5, 7, 3]
output:
2, -4 #the difference between 5 and 7, then the difference between 7 and 3
CodePudding user response:
If using python ≥ 3.10 there is the builtin itertools.pairwise
:
from itertools import pairwise
lst = [5, 7, 3]
[b-a for a,b in pairwise(lst)]
Output: [2, -4]
NB. If python < 3.10, there is a recipe for pairwise in the documentation (see above link)
CodePudding user response:
Try zip()
:
lst = [5, 7, 3]
print([j - i for i, j in zip(lst[:-1], lst[1:])])
Output:
[2, -4]
Explanation:
The built-in
zip()
function will iterate over any number of iterables passed into it in parallel, producing tuples with an item from each one.Passing in
lst[:-1]
andlst[1:]
will produce every element in thelst
array beside the very next element in the array.Finally,
j - i for i, j in zip(lst[:-1], lst[1:])
will unpack the adjacent elements and find their difference.