Skip to content Skip to sidebar Skip to footer

Finding The Difference Between Consecutive Numbers In A List (python)

Given a list of numbers, I am trying to write a code that finds the difference between consecutive elements. For instance, A = [1, 10, 100, 50, 40] so the output of the function s

Solution 1:

You can do:

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


>>>A = [1, 10, 100, 50, 40]>>>[y-x for x, y inzip(A[:-1], A[1:])]
[9, 90, -50, -10]

Note that the difference will be negative if the right side is smaller, you can easily fix this (If you consider this wrong), I'll leave the solution for you.

Explanation:

The best explanation you can get is simply printing each part of the list comprehension.

  • A[:-1] returns the list without the last element: [1, 10, 100, 50]
  • A[1:] returns the list without the first element: [10, 100, 50, 40]
  • zip(A[:-1], A[1:]) returns [(1, 10), (10, 100), (100, 50), (50, 40)]
  • The last step is simply returning the difference in each tuple.

Solution 2:

The simplest (laziest) solution is to use the numpy function diff:

>>>A = [1, 10, 100, 50, 40]>>>np.diff(A)
array([  9,  90, -50, -10])

If you want the absolute value of the differences (as you've implied by your question), then take the absolute value of the array.

Solution 3:

[abs(j-A[i+1]) for i,j in enumerate(A[:-1])]

Solution 4:

You can do a list comprehension:

>>>A = [1, 10, 100, 50, 40]>>>l=[A[0]]+A>>>[abs(l[i-1]-l[i]) for i inrange(1,len(l))]
[0, 9, 90, 50, 10]

Solution 5:

For a longer recursive solution more in line with your original approach:

defdeviation(A) :
    iflen(A) < 2 :
        return []
    else :
        return [abs(A[0]-A[1])] + deviation(A[1:])

Your bracket issue is with your recursive call. Since you have your [deviation(a[1: ])] in its own [] brackets, with every recursive call you're going to be creating a new list, resulting in your many lists within lists.

In order to fix the None issue, just change your base case to an empty list []. Now your function will add 'nothing' to the end of your recursively made list, as opposed to the inherent None that comes with a blank return'

Post a Comment for "Finding The Difference Between Consecutive Numbers In A List (python)"