Home > Mobile >  Subtract values at each index from list in python [closed]
Subtract values at each index from list in python [closed]

Time:10-01

Hi I want to get values of x at each index from x to calculate y preferably using a for loop for all indexes

x = [1,2,3,4,5,6,7,8,9,10]
indexes_for_x =[0,1,2,3]

#subtract values of x at each index from x to calculate y
# for index 0 since x = 1 result should look like below
y_at_index_0 = [0,1,2,3,4,5,6,7,8,9]

CodePudding user response:

I hope I've understood your question right. If you want to subtract each value from x[<indexes_for_x>] then you can do:

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
indexes_for_x = [0, 1, 2, 3]

for v in indexes_for_x:
    print(f"y_at_index_{v} = {[w - x[v] for w in x]}")

Prints:

y_at_index_0 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y_at_index_1 = [-1, 0, 1, 2, 3, 4, 5, 6, 7, 8]
y_at_index_2 = [-2, -1, 0, 1, 2, 3, 4, 5, 6, 7]
y_at_index_3 = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
  • Related