Home > other >  Difference of integers within a list?
Difference of integers within a list?

Time:10-25

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:

  1. 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.

  2. Passing in lst[:-1] and lst[1:] will produce every element in the lst array beside the very next element in the array.

  3. Finally, j - i for i, j in zip(lst[:-1], lst[1:]) will unpack the adjacent elements and find their difference.

  • Related