Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create list by subtracting the nth+1 value from the nth values of another list

I need to create a list which returns the difference between the nth and nth + 1 values of another list. Is there any way of simplifying the code below to work for any size lists?

mylist = [1,5,15,30,60]

w = mylist[1] - mylist[0]
x = mylist[2] - mylist[1]
y = mylist[3] - mylist[2]
z = mylist[4] - mylist[3]

difflist = [w,x,y,z]

print difflist

And this will return [4,10,15,30]

like image 709
Chuck M Avatar asked Oct 19 '17 19:10

Chuck M


1 Answers

Take a look at this one:

mylist = [1,5,15,30,60]

def diff(myList):
    return [myList[i+1] - myList[i] for i in range(len(myList)-1)]

l = diff(mylist)
print(l) 

The output is:

[4, 10, 15, 30]
like image 187
Vasilis G. Avatar answered Oct 04 '22 21:10

Vasilis G.