0

I apologize for the poorly worded title, but I am very new to Python and coding in general. I'm assuming that my question is simple, but I haven't been able to find the help I am looking for. Here is the code I have right now:

for i in xList:
    dif == (xList[i+1] - i)

What I am trying to do is take all of the values in the list, find the difference between each value, and then find the average difference. Please provide any help. Thank you for your time!

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
DOM
  • 53
  • 1
  • 8

2 Answers2

0

The average difference is the sum of differences divided by the count.

count = len(xList) - 1
total_diff = 0
for i in range(count):
    a = xList[i]
    b = xList[i+1]
    total_diff += abs(a - b) # absolute value, so negatives don't cancel positives

print(total_diff / count)
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • For the range, you use the variable 'count', which you set equal to the length of the list minus 1. If the list contained the values 1,3,4, would it go through 1, 3, 4 since these are the values, or would it go through 0, 1, 2 since 3 is the length? Also, does the +=, following the variable 'total_diff', mean that you are adding the previous total difference to the new one each iteration, which, in turn, will give the final total difference after all iterations? – DOM Mar 18 '17 at 04:01
  • @PierceForte: Why don't you just try it and see for yourself? – John Zwinck Mar 18 '17 at 04:15
0

zip makes it easy to walk through the list looking at each consecutive pair of elements:

diff_sum = 0
for a, b in zip(xlist, xlist[1:]):
    diff_sum += abs(b-a)

You can even collapse this further using a generator expression and the sum built-in:

diff_sum = sum(abs(b-a) for a,b in zip(xlist, xlist[1:]))

Now divide by the length of the list minus 1:

ave_diff = diff_sum / (len(xlist)-1)

(Of course, a single-element list will give you divide by zero, so you'll want to guard against that.)

PaulMcG
  • 62,419
  • 16
  • 94
  • 130
  • OP doesn't know the difference between `==` and `=` or between a list index and a list element. Maybe not necessary to bring generators, zip, and slicing into it just yet! – John Zwinck Mar 18 '17 at 04:16