Home > Blockchain >  How to sum and print difference of each element in list in python
How to sum and print difference of each element in list in python

Time:01-23

I have a list of numbers in python, and I want to find the difference between each number, add it up, then print it. For example, if the list was [1,3,4,7,8] the difference between 1 and 3 is 2 so it would store 2 in a list somewhere, then the difference between 3 and 4 is 1, and would store 4 in the same list as the two. It would keep doing that until the difference between 7 and 8 is found, then add all of the differences and print them (which would be 7 for this example). This is what I have so far.


your text numbers = [1,2,3,4]
total = []
for i in len(numbers):
    dif = numbers[i 1]-numbers[i]
    total.append(dif)
    print(sum(total))
    break

This code is in python. It was meant to print 3 because of all the differences added up, but only printed 1.

CodePudding user response:

A simple approach would be to iterate through the list and append the difference to a secondary list with the difference being calculated with abs()

a = [1, 3, 4, 7, 8]
b = []

for i in range(0, len(a)-1):
    b.append(abs(a[i] - a[i 1]))

sum_diffs = sum(b)

Which would return 7 :)

CodePudding user response:

You can use a combination of two built-in functions:- sum() and zip() as follows:

numbers = [1,3,4,7,8]

print(sum(y-x for x, y in zip(numbers, numbers[1:])))

Output:

7

CodePudding user response:

Try this:

numbers = [1,2,3,4]
a= numbers[0]
b=[]
for i in numbers:
     v= i-a
     b.append(v)
     a=i
print(sum(b))
  • Related