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]
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With