Skip to content
Advertisement

(python) subtract value in a list from value in the same list in a for loop / list comprehension

suppose i have

list1 = [3, 4, 6, 8, 13]

in a for loop I want to subtract the value i from the value that comes right after. In the above example: 4-3, 6-4, 8-6, 13-8. (and i want to skip the first value) desired result

list2 = [3, 1, 2, 2, 5]

can i do this in a for loop / list comprehension?

more specifically do I want to do this in a dataframe


   list1 
0     3   
1     4   
2     6   
3     8   
4     13

and after the operation

   list1    list2 
0     3       3  
1     4       1   
2     6       2  
3     8       2 
4     13      5

I have tried for loops, lambda functions and list comprehensions and trying to access the positional index with enumerate() but I can’t figure out how to access the value just before the value from which I want to subtract from

edit: answers below worked. thank you very much!

Advertisement

Answer

You should use shift to access the next row:

df['list2'] = df['list1'].sub(df['list1'].shift(fill_value=0))

Or, using diff with fillna:

df['list2'] = df['list1'].diff().fillna(df['list1'])

Output:

   list1  list2
0      3      3
1      4      1
2      6      2
3      8      2
4     13      5

For a pure python solution:

list1 = [3, 4, 6, 8, 13]

list2 = [a-b for a,b in zip(list1, [0]+list1)]

Output: [3, 1, 2, 2, 5]

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement