Home > front end >  (python) subtract value in a list from value in the same list in a for loop / list comprehension
(python) subtract value in a list from value in the same list in a for loop / list comprehension

Time:11-09

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!

CodePudding user response:

The dataframe solution has already been posted. This is an implementation for lists:

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

list2 = []
for i, v in enumerate(list1):
    list2.append(list1[i] - list1[i-1])
list2[0] = list1[0]

print(list2)  # [3, 1, 2, 2, 5]

And lastly, in list comprehension:

list2 = [list1[i] - list1[i-1] for i, v in enumerate(list1)]
list2[0] = list1[0]

CodePudding user response:

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]

CodePudding user response:

You could loop backwards for x in range(len(list) - 1, 0, -1): and then the calculation can be done list[x] = list[x] - list[x - 1]

CodePudding user response:

Try this code its working

import pandas as pd

list1 = [3, 4, 6, 8, 13]
list2 = [list1[i 1]-list1[i] for i in range(len(list1)-1)]
list2.insert(0, list1[0])

data = {
    "list1":list1, 
    "list2":list2
}

df = pd.DataFrame(data)
print(df)

output:

$ python3 solution.py 
   list1  list2
0      3      3
1      4      1
2      6      2
3      8      2
4     13      5

  • Related