Skip to content Skip to sidebar Skip to footer

How To Subtract The Next Value From The Previous Value In Python?

I want to subtract the previous value from the next value in a list and finally add the out put into a dictionary. Example: # Original List l= [1, 10, 25, 35, 55, 100] # Expected O

Solution 1:

Here is what you need to do

l= [1, 10, 25, 35, 55, 100]
nl = [(n-l[i-1]) if i else n for i,n in enumerate(l)]
lst = ['col1', 'col2', 'col3', 'col4', 'col5']
final = dict(zip(lst, nl))
Out[460]: {'col1': 1, 'col2': 9, 'col3': 15, 'col4': 10, 'col5': 20}

Post a Comment for "How To Subtract The Next Value From The Previous Value In Python?"